Comparison on Inheritance and Polymorphism

Comparison on Inheritance and Polymorphism

Inheritance allows, code reusability and the polymorphism is, the occurrence of one function with different form. The basic difference between inheritance and polymorphism is that inheritance allows the already existing code to be reused again in a program, and polymorphism provides a mechanism to dynamically decide what form of a function to be invoke

Inheritance and polymorphism


Definition of Inheritance

Inheritance is one of the crucial features of OOP, which strongly support “reusability”. Reusability could be described as creating a new class by reusing the properties of the existing class. In inheritance, there is a base class, which is inherited by the derived class. When a class inherits any other class, the member(s) of the base class becomes the member(s) of a derived class.

Inheritance in Object Oriented Programming

OOPs is a style of computer programming which represents concepts as objects that have state and behavior. Inheritance is one of the most important features of Object-Oriented Programming Languages whether it is Java, C++, or any other OOP language. But what is Inheritance and its need?

Inheritance can be defined as a mechanism by which one object can acquire all the properties (i.e., data members) and behaviour (i.e., member functions or methods) of a parent object to reduce code redundancy. But how does it reduce code redundancy let us see with an example. Suppose you are creating a project where you have many classes now there are some methods which are repeated in many classes so would it be feasible to rewrite the same method again and again in each class? Off course not. So, this is where inheritance comes into picture, we create a class which has the method which is repeated and rather than rewriting the same method again and again we can simply extend that class i.e., inherit its property to other classes. Now as you can see this creates an IS-A relationship, so inheritance is sometimes referred as

is-a relation between class where the class which inherits some methods or behavior from another class in called a child class or subclass and the class from which it extends some properties is called parent class or superclass

 

 

Inheritance in Java

 

Inheritance in java can be achieved using the extends keywords see the example given below

 

 class Human{
   
int numberOfEyes=2;
   
int NumberOfHands=2;
   
int NumberOfLegs=2;
   
void sleep(String human,int hours){
       
System.out.println(human+" Sleeps "+hours+" hours in a day");
    }
}
class Sohail extends Human{
   
String name="Sohail";

}

public class Main {

   
public static void main(String[] args) {
       
Sohail s=new Sohail();
       
System.out.println("Sohail has "+s.numberOfEyes+" Eyes");
        s.
sleep(s.name,7);

    }
}

 

Output :

Now in the above example you can see that we used the extends keyword for class Sohail and inherit some behavior and methods from Human class

Such as sleep method so we can clearly see now from the above example that Sohail class is the subclass of Human class, and an IS-A relation is established between two classes i.e., Sohail IS-A human. Now let us move to the type of inheritance.

 

Types of Inheritance


1.Single Inheritance: 

     This is the simplest type of inheritance when there is a single parent class and child class. Sometimes it is also known as simple inheritanceAs you can see in the above picture A is the parent class(base class ) of 

 

2.Multilevel inheritance

    In Multilevel inheritance there are classes which are derived from the base class and these derived classes can act as base class for another class. It’s like a grandfather, father and child relation. Hence, there exists a single base class and single derived class but multiple intermediate base class.


3.Hierarchical Inheritance:

     Hierarchical inheritance example in real world can be multiple children of a father they all inherit some property from their father similarly we can have multiple sub classes which extends a single base class.


4.Muliple inheritance:

         Real world example of Multiple inheritance can be a child can inherit properties from both the parents. Similarly in programming a single class can inherit properties from multiple base classes. Now this type of inheritance is not supported in java as we can have methods with same name in both parent class so it will create ambiguity that which method to inherit. There is a provision in java to achieve multiple inheritance through 

 

5.Hybrid inheritance:

                 Hybrid inheritance can be considered as the combination of 2 or more types of above-mentioned inheritance.


 

Important facts about inheritance in Java :

Ø  Inheriting Constructors: A subclass inherits all the members (fields, methods, and nested classes) from its superclass. Constructors are not members, so they are not inherited by subclasses, but the constructor of the superclass can be invoked from the subclass. 

Ø Private member inheritance: A subclass does not inherit the private members of its parent class. However, if the superclass has public or protected methods (like getters and setters) for accessing its private fields, these can also be used by the subclass.

 

Advantages and Disadvantages of inheritance:

Advantages:

o   Code reusability

o   By inheritance we can achieve dynamic polymorphism i.e method overriding

Disadvantages:

o   Using inheritance, the parent and child class gets tightly coupled 

Polymorphism

Polymorphism is the ability of an object to take on many forms. The word polymorphism is derived from 2 words: Poly and morphs. The word “poly” means many and “morphs” mean forms. So, Word polymorphism means many forms. In chemistry, the term polymorphism means that an object can exist in different crystalline forms. For example, Carbon can exist in three types. Coal, graphite, and diamond are the three different crystalline forms of carbon.

Polymorphism is one of the most important principals of OOPs. In Java, polymorphism is a phenomenon of an object that can exhibit a property of performing operations from different perspectives.

Real Life example of polymorphism in java:

You can see in the below image, different roles of a teacher. Teacher is only one, but he/she takes multiple roles like- he/she is a guide, a lecturer, an assistant, a friend, a son/daughter, a father/mother, an interviewer and many more. This is known as polymorphism.

When different people enter an organization, a security guard outside the organization acts differently. When the boss arrives, he acts one way, and when the employees arrive, he acts another way. When the customers arrive, the guard will act in a unique way. As a result, the guard's demeanour varies depending on the individual who is arriving.

 

Types of polymorphism:

 

1. Static/Compile-Time Polymorphism

When a polymorphism is resolved by the compiler during the compilation of a programme, we refer to it as compile-time polymorphism or static polymorphism. Static binding is another name for it.

Method Overloading in Java can be used to implement or accomplish compile-time/static polymorphism.

 

Let’s see what Method Overloading is:

If a class has two or more methods with the same name but different order or number of parameters, it is called method overloading. In Java, you can give a function the same name if you can distinguish it by the number and type of arguments.

For example, the following functions are different in Java:

float divide (int a, int b) {...}

float divide (float x, float y){...}

float divide (float a, int b) {...}

That is, the Divide () function with two Int arguments is different from Divide () with two Float arguments, and it is also different from Divide () with Int and Float arguments. This is known as function overloading.

 

 

 

 

 

 

 

 

 

package com.vit.polymorphism;

public class MethodOverloading {

 

     public static void main(String[] args) {

           int a=2;

           int b=5;

           double c=2.5;

           double d=5.5;

           int res1=MethodOverloading.fun(a,b);

           System.out.println("The addition of two integer type number is "+res1);

           double res2=MethodOverloading.fun(c,d);

           System.out.println("The addition of two double type number is "+res2);

 

     }

     static int fun(int a,int b) {

           return a+b;

     }

     static double fun(double a,double b) {

           return a+b;

     }

 

}

 

Output:

2. Dynamic/Run-Time Polymorphism

Run-time or dynamic polymorphism is polymorphism that is dynamically resolved at run time and is not called at compile time. This is also known as dynamic binding or dynamic method dispatch. This type of polymorphism is called run-time or dynamic polymorphism because method calls are made at run time rather than at compile time. You can achieve dynamic polymorphism in Java by using the method override.

 In object-oriented languages, method overrides occur when a derived class provides a specific definition for a method that already exists in its parent class. Indicates that the base class function will be overridden.

 If you define a base class method with the same name and parameters, and if you define the same return type in a child or derived class, the subclass method overrides the superclass method. This process is a method that you override in Java.

Note: You cannot achieve run-time polymorphism using data members. It can only be achieved by the method.

Code to illustrate Method/function Overriding:

package com.vit.polymorphism;

class Shape

{

  void area()

  {

    System.out.println("Area of Shape");

  }

}

class Square extends Shape

{

  //Overriding method of base class with different implementation

  void area()

  {

    System.out.println("Area of Square");

  }

}

class Circle extends Shape

{

  //Overriding method of base class with different implementation

  void area()

  {

    System.out.println("Area of Circle");

  }

}

class Triangle extends Shape

{

  //Overriding method of base class with different implementation

  void area()

  {

    System.out.println("Area of Triangle");

  }

}

public class MethodOverriding

{

  public static void main(String args[])

  {

    //creating object of Base class Shape

    Shape obj ;

    obj=new Shape();

    obj.area();

    //initiating object with subclasses

    obj=new Square();

    obj.area();

    obj=new Circle();

    obj.area();

    obj=new Triangle();

    obj.area();

  }

}

Output:

Use of Java Polymorphism:

Polymorphism allows you to create methods that correctly handle different types of features with the same name. Polymorphism also allows for code consistency.

For example,

Suppose you need to execute the Dog and Cat animalSound () method. To do this, create a `Animal` class and expand it into two subclasses, Dog and Cat. In this case, it makes more sense to create an animalSound() method with the same name in both subclasses than to create a method with a different name.

Advantages of Java Polymorphism

·       Polymorphism allows a superclass to define methods common to all derived classes, whereas a subclass can define additional implementations of some or all these methods.

·       Method overriding is supported by dynamic binding or dynamic polymorphism, a key aspect of runtime polymorphism.

·       Polymorphism allows a method to do different things depending on the object it operates on.


Comparison Chart

BASIS FOR COMPARISON

INHERITANCE

POLYMORPHISM

Basic

Inheritance is creating a new class using the properties of the already existing class.

Polymorphism is basically a common interface for multiple form.

Implementation

Inheritance is basically implemented on classes.

Polymorphism is basically implemented on function/methods.

Use

To support the concept of reusability in OOP and reduces the length of code.

Allows object to decide which form of the function to be invoked when, at compile time(overloading) as well as run time(overriding).

Forms

Inheritance may be a single inheritance, multiple inheritance, multilevel inheritance, hierarchical inheritance and hybrid inheritance.

Polymorphism may be a compile time polymorphism (overloading) or run-time polymorphism (overriding).

Example

The class 'table' can inherit the feature of the class 'furniture', as a 'table' is a 'furniture'.

The class 'study_table' can also have function 'set_color()' and a class 'Dining_table' can also have function 'set_color()' so, which form of the set_color() function to invoke can be decided at both, compile time and run time.

 

 

 

 

 

 

 

 

 

 

Key Differences Between Inheritance and Polymorphism

1.   Inheritance is creating a class that derives its feature from an already existing class. On the other hand, polymorphism is an interface that can be defined in multiple forms.

2.   Inheritance is implemented on the classes whereas, the polymorphism is implemented on methods/functions.

3.   As inheritance allows a derived class to use the elements and methods defined in the base class, the derived class does not need to define those 

Comparison Inheritance and Polymorphism

Inheritance allows, code reusability and the polymorphism is, the occurrence of one function with different form. The basic difference between inheritance and polymorphism is that inheritance allows the already existing code to be reused again in a program, and polymorphism provides a mechanism to dynamically decide what form of a function to be invoked.

Definition of Inheritance

Inheritance is one of the crucial features of OOP, which strongly support “reusability”. Reusability could be described as creating a new class by reusing the properties of the existing class. In inheritance, there is a base class, which is inherited by the derived class. When a class inherits any other class, the member(s) of the base class becomes the member(s) of a derived class.

Inheritance in Object Oriented Programming

OOPs is a style of computer programming which represents concepts as objects that have state and behavior. Inheritance is one of the most important features of Object-Oriented Programming Languages whether it is Java, C++, or any other OOP language. But what is Inheritance and its need?

Inheritance can be defined as a mechanism by which one object can acquire all the properties (i.e., data members) and behaviour (i.e., member functions or methods) of a parent object to reduce code redundancy. But how does it reduce code redundancy let us see with an example. Suppose you are creating a project where you have many classes now there are some methods which are repeated in many classes so would it be feasible to rewrite the same method again and again in each class? Off course not. So, this is where inheritance comes into picture, we create a class which has the method which is repeated and rather than rewriting the same method again and again we can simply extend that class i.e., inherit its property to other classes. Now as you can see this creates an IS-A relationship, so inheritance is sometimes referred as

is-a relation between class where the class which inherits some methods or behavior from another class in called a child class or subclass and the class from which it extends some properties is called parent class or superclass

 

 

Inheritance in Java

 

Inheritance in java can be achieved using the extends keywords see the example given below

 

 class Human{
   
int numberOfEyes=2;
   
int NumberOfHands=2;
   
int NumberOfLegs=2;
   
void sleep(String human,int hours){
       
System.out.println(human+" Sleeps "+hours+" hours in a day");
    }
}
class Sohail extends Human{
   
String name="Sohail";

}

public class Main {

   
public static void main(String[] args) {
       
Sohail s=new Sohail();
       
System.out.println("Sohail has "+s.numberOfEyes+" Eyes");
        s.
sleep(s.name,7);

    }
}

 

Output :

 

Now in the above example you can see that we used the extends keyword for class Sohail and inherit some behavior and methods from Human class

Such as sleep method so we can clearly see now from the above example that Sohail class is the subclass of Human class, and an IS-A relation is established between two classes i.e., Sohail IS-A human. Now let us move to the type of inheritance.

 

Types of Inheritance

1.Single Inheritance: This is the simplest type of inheritance when there is a single parent class and child class. Sometimes it is also known as simple inheritance.

As you can see in the above picture A is the parent class(base class ) of B

 

2.Multilevel inheritance: In Multilevel inheritance there are classes which are derived from the base class and these derived classes can act as base class for another class. It’s like a grandfather, father and child relation. Hence, there exists a single base class and single derived class but multiple intermediate base classes.

 

 

3.Hierarchical Inheritance: Hierarchical inheritance example in real world can be multiple children of a father they all inherit some property from their father similarly we can have multiple sub classes which extends a single base class.

4.Muliple inheritance: Real world example of Multiple inheritance can be a child can inherit properties from both the parents. Similarly in programming a single class can inherit properties from multiple base classes. Now this type of inheritance is not supported in java as we can have methods with same name in both parent class so it will create ambiguity that which method to inherit. There is a provision in java to achieve multiple inheritance through interfaces  

 

 

 

5.Hybrid inheritance: Hybrid inheritance can be considered as the combination of 2 or more types of above-mentioned inheritance.

 

In the above example the combination of two inheritance Hierarchical and Multiple inheritance and as you can see a diamond shape is formed and multiple inheritance not being supported by java this is called diamond problem.

 

Important facts about inheritance in Java :

Ø  Inheriting Constructors: A subclass inherits all the members (fields, methods, and nested classes) from its superclass. Constructors are not members, so they are not inherited by subclasses, but the constructor of the superclass can be invoked from the subclass.

Ø  Private member inheritance: A subclass does not inherit the private members of its parent class. However, if the superclass has public or protected methods (like getters and setters) for accessing its private fields, these can also be used by the subclass.

 

Advantages and Disadvantages of inheritance:

Advantages:

o   Code reusability

o   By inheritance we can achieve dynamic polymorphism i.e method overriding

Disadvantages:

o   Using inheritance, the parent and child class gets tightly coupled

 

 

 

Polymorphism

Polymorphism is the ability of an object to take on many forms. The word polymorphism is derived from 2 words: Poly and morphs. The word “poly” means many and “morphs” mean forms. So, Word polymorphism means many forms. In chemistry, the term polymorphism means that an object can exist in different crystalline forms. For example, Carbon can exist in three types. Coal, graphite, and diamond are the three different crystalline forms of carbon.

Polymorphism is one of the most important principals of OOPs. In Java, polymorphism is a phenomenon of an object that can exhibit a property of performing operations from different perspectives.

Real Life example of polymorphism in java:

You can see in the below image, different roles of a teacher. Teacher is only one, but he/she takes multiple roles like- he/she is a guide, a lecturer, an assistant, a friend, a son/daughter, a father/mother, an interviewer and many more. This is known as polymorphism.

When different people enter an organization, a security guard outside the organization acts differently. When the boss arrives, he acts one way, and when the employees arrive, he acts another way. When the customers arrive, the guard will act in a unique way. As a result, the guard's demeanor varies depending on the individual who is arriving.

 

Types of polymorphism:

 

1. Static/Compile-Time Polymorphism

When a polymorphism is resolved by the compiler during the compilation of a program , we refer to it as compile-time polymorphism or static polymorphism. Static binding is another name for it.

Method Overloading in Java can be used to implement or accomplish compile-time/static polymorphism.

 

Let’s see what Method Overloading is:

If a class has two or more methods with the same name but different order or number of parameters, it is called method overloading. In Java, you can give a function the same name if you can distinguish it by the number and type of arguments.

For example, the following functions are different in Java:

float divide (int a, int b) {...}

float divide (float x, float y){...}

float divide (float a, int b) {...}

That is, the Divide () function with two Int arguments is different from Divide () with two Float arguments, and it is also different from Divide () with Int and Float arguments. This is known as function overloading.

 

 

 

 

 

 

 

 

 

package com.vit.polymorphism;

public class MethodOverloading {

 

     public static void main(String[] args) {

           int a=2;

           int b=5;

           double c=2.5;

           double d=5.5;

           int res1=MethodOverloading.fun(a,b);

           System.out.println("The addition of two integer type number is "+res1);

           double res2=MethodOverloading.fun(c,d);

           System.out.println("The addition of two double type number is "+res2);

 

     }

     static int fun(int a,int b) {

           return a+b;

     }

     static double fun(double a,double b) {

           return a+b;

     }

 

}

 

Output:

the addition of two integer type number is 7

the addition of two double type number is 8.0




2. Dynamic/Run-Time Polymorphism

Run-time or dynamic polymorphism is polymorphism that is dynamically resolved at run time and is not called at compile time. This is also known as dynamic binding or dynamic method dispatch. This type of polymorphism is called run-time or dynamic polymorphism because method calls are made at run time rather than at compile time. You can achieve dynamic polymorphism in Java by using the method override.

 In object-oriented languages, method overrides occur when a derived class provides a specific definition for a method that already exists in its parent class. Indicates that the base class function will be overridden.

 If you define a base class method with the same name and parameters, and if you define the same return type in a child or derived class, the subclass method overrides the superclass method. This process is a method that you override in Java.

Note: You cannot achieve run-time polymorphism using data members. It can only be achieved by the method.

Code to illustrate Method/function Overriding:

package com.vit.polymorphism;

class Shape

{

  void area()

  {

    System.out.println("Area of Shape");

  }

}

class Square extends Shape

{

  //Overriding method of base class with different implementation

  void area()

  {

    System.out.println("Area of Square");

  }

}

class Circle extends Shape

{

  //Overriding method of base class with different implementation

  void area()

  {

    System.out.println("Area of Circle");

  }

}

class Triangle extends Shape

{

  //Overriding method of base class with different implementation

  void area()

  {

    System.out.println("Area of Triangle");

  }

}

public class MethodOverriding

{

  public static void main(String args[])

  {

    //creating object of Base class Shape

    Shape obj ;

    obj=new Shape();

    obj.area();

    //initiating object with subclasses

    obj=new Square();

    obj.area();

    obj=new Circle();

    obj.area();

    obj=new Triangle();

    obj.area();

  }

}

Output:

Area of shape

Area of Square

Area of triangle

Area of circle


Use of Java Polymorphism:

Polymorphism allows you to create methods that correctly handle different types of features with the same name. Polymorphism also allows for code consistency.

For example,

Suppose you need to execute the Dog and Cat animalSound () method. To do this, create a `Animal` class and expand it into two subclasses, Dog and Cat. In this case, it makes more sense to create an animalSound() method with the same name in both subclasses than to create a method with a different name.

Advantages of Java Polymorphism

·       Polymorphism allows a superclass to define methods common to all derived classes, whereas a subclass can define additional implementations of some or all these methods.

·       Method overriding is supported by dynamic binding or dynamic polymorphism, a key aspect of runtime polymorphism.

·       Polymorphism allows a method to do different things depending on the object it operates on.


Comparison Chart

BASIS FOR COMPARISON

INHERITANCE

POLYMORPHISM

Basic

Inheritance is creating a new class using the properties of the already existing class.

Polymorphism is basically a common interface for multiple form.

Implementation

Inheritance is basically implemented on classes.

Polymorphism is basically implemented on function/methods.

Use

To support the concept of reusability in OOP and reduces the length of code.

Allows object to decide which form of the function to be invoked when, at compile time(overloading) as well as run time(overriding).

Forms

Inheritance may be a single inheritance, multiple inheritance, multilevel inheritance, hierarchical inheritance and hybrid inheritance.

Polymorphism may be a compile time polymorphism (overloading) or run-time polymorphism (overriding).

Example

The class 'table' can inherit the feature of the class 'furniture', as a 'table' is a 'furniture'.

The class 'study_table' can also have function 'set_color()' and a class 'Dining_table' can also have function 'set_color()' so, which form of the set_color() function to invoke can be decided at both, compile time and run time.

 

 

 

 

 

 

 

 

 

 

Key Differences Between Inheritance and Polymorphism

1.   Inheritance is creating a class that derives its feature from an already existing class. On the other hand, polymorphism is an interface that can be defined in multiple forms.

2.   Inheritance is implemented on the classes whereas, the polymorphism is implemented on methods/functions.

3.   As inheritance allows a derived class to use the elements and methods defined in the base class, the derived class does not need to define those elements or method it again so, we can say it increases code reusability and hence, reduces the length of the code. On the other hand, polymorphism makes it possible for an object to decide what form of the method it wants to invoke at both compile-time and run time.

4.   The inheritance can be classified as single inheritance, multiple inheritance, multilevel inheritance, hierarchical inheritance and hybrid inheritance. On the other hand, polymorphism is classified as overloading and overriding.

Conclusion

The Inheritance and polymorphism are interrelated concepts, as the dynamic polymorphism applies to the classes which also implement the concept of inheritance.

 

 elements or method it again so, we can say it increases code reusability and hence, reduces the length of the code. On the other hand, polymorphism makes it possible for an object to decide what form of the method it wants to invoke at both compile-time and run time.

4.   The inheritance can be classified as single inheritance, multiple inheritance, multilevel inheritance, hierarchical inheritance and hybrid inheritance. On the other hand, polymorphism is classified as overloading and overriding.



Conclusion :

The Inheritance and polymorphism are interrelated concepts, as the dynamic polymorphism applies to the classes which also implement the concept of inheritance.

 

 


Comments