Suppose I have two classes: Animal and Dog. Dog is a subclass of Animal. I do the following code:
Animal a = new Dog();
Now I can call methods of the Dog class through the a variable.
But my question is this: if I can call all of Animal's methods through the Dog objects (inheritance) than why should I use the polymorphism principle? I can just declare:
Dog d = new Dog();
With this declaration can use all of Animal's methods and Dog methods. So why use polymorphism? Thank you very much for your answer.
Inheritance is one in which a new class is created (derived class) that inherits the features from the already existing class(Base class). Whereas polymorphism is that which can be defined in multiple forms.
Real polymorphism in General can not be acheived without inheritance. Languages that are not object-oriented provide forms of polymorphism which do not rely on inheritance (i.e parametric polymorphism).
A real-life example of polymorphism is a person who at the same time can have different characteristics. A man at the same time is a father, a husband, and an employee. So the same person exhibits different behavior in different situations. This is called polymorphism.
In Java, the concepts of polymorphism and inheritance are "welded together"; in general, it does not have to be that way:
There are languages where inheritance is decoupled from polymorphism:
virtual
)Going back to Java, the reason to use polymorphism is decoupling your code from the details of the implementation of its counter-parties: for example, if you can write a method Feed(Animal animal)
that works for all sorts of animals, the method would remain applicable when you add more subclasses or implementations of the Animal
. This is in contrast to a Feed(Dog dog)
method, that would be tightly coupled to dogs.
As far as the
Dog d = new Dog();
declaration goes, there is no general reason to avoid this if you know that the rest of your method deals specifically with dogs. However, in many cases the later is not the case: for example, your class or your methods would often be insensitive to the exact implementation, for example
List<Integer> numbers = new ArrayList<Integer>();
In cases like that, you can replace new ArrayList<Integer>()
with new LinkedList<Integer>()
, and know that your code is going to compile. In contrast, had your numbers
list been declared as ArrayList<Integer> numbers
, such switchover may not have been a certainty.
This is called "programming to an interface". There is a very good answer on Stack Overflow explaining it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With