INHERITANCE AND POLYMORPHISM IN JAVA

 


 

horizontal line

INHERITANCE AND POLYMORPHISM IN JAVA



Inheritance and polymorphism are two important concepts in object-oriented programming, particularly in Java. Both concepts are used to create relationships between classes and can help make code more efficient, readable and easier to maintain. In this blog, we will explore the differences between inheritance and polymorphism and their usage in Java.



Inheritance in Java:

Inheritance is a mechanism in Java that allows a class to inherit properties and behaviors from another class. The class that is being inherited from is called the parent or super class, and the class that is inheriting is called the child or sub class. Inheritance allows the child class to reuse code from the parent class and also enables the child class to add its own unique properties and behaviors.

  • Syntax :

In Java, the syntax for inheritance is as follows:

Here, the keyword ‘extends' is used to establish inheritance between the child and parent class. The child class has access to all the non-private properties and methods of the parent class.


  • Example :

In the above example, Dog is a child class of Animal and it inherits the eat() method from the Animal class. The Dog class also has its own unique method bark(), which is not present in the Animal class.



Polymorphism in Java :

Polymorphism is a concept in Java that allows objects of different classes to be treated as if they were of the same class. It is achieved through method overriding and method overloading.


  • Method Overriding :

Method overriding is when a child class provides its own implementation for a method that is already defined in the parent class. When a method is overridden, the child class method is called instead of the parent class method.

  • Syntax :

  • Example :


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.



References :

Comments