Programmers often confused among different object oriented concepts e.g. between Composition and Inheritance, between
abstraction and encapsulation and some-time between
Polymorphism and Inheritance. In this article, we will explore third one, Polymorphism vs Inheritance. Like in real world, Inheritance is used to define relationship between two classes. It's similar to Father-Son relationship. In object oriented programming, we have a Parent class (also known as super class) and a Child class (also known as sub class). Similar to real world, Child inherit Parents qualities, e.g. it's attribute, methods and code. Inheritance is actually meant for code-reuse. Child can reuse all the codes written in Parent class, and only write code for behaviour which is different than parent. Though it’s possible to restrict something to parent itself by using
private and
final keyword in Java. On the other hand,
Polymorphism is an ability of Object to behave in multiple form. For example a Parent variable can hold reference of either a Parent object or a Child object, so when you call a virtual method on Parent's object, it may go to child's method depending upon which kind of object it is pointing at runtime. This is known as Polymorphism, and one of the most popular form of Polymorphism is
method overriding in Java. By the way, If you look closely they are actually related to each other, because its Inheritance which makes Polymorphism possible, without any relationship between two class, it's not possible to write polymorphic code, which can take advantage of runtime binding of different objects. You cannot use Polymorphism on something which is not inherited by Child class e.g.
private method can't be overridden in Java. Let's take an example to understand difference between Polymorphism and Inheritance in Java more closely.