Reputation: 13
I have been reading about dynamic polymorphism in java recently(I am beginner). As per my understanding if a reference of a parent class type is assigned as a reference to its child like below
tutorialspoint it involves dynamic polymorphism. In the example discussed in the link, I understand an Object of employee class is used to access a (overridden) method of salary class. In that example neither is employee abstract nor is an interface. (which means it is possible to create an object for the parent).
Now, as per this link stackoverflow, I see that an interface is used to discuss dynamic polymorphism.
Question: How is it possible to use interface as an example for dynamic polymorphism?
Moreover, in the example discussed in tutorialspoint, it is said that compiler look for the method in parent class but JVM invokes the child class method during run time.
Interfaces neither have method definition nor can be instantiated, so how can
List<Animal> animalPen = new LinkedList<>();
be used for dynamic polymorphism.
Upvotes: 1
Views: 1185
Reputation: 25
You use interfaces to do polymorphism when you have different behaviours in your objects. Let's say you have a class Duck and you have a FlyBehavior variable declared. In this case the first thing you think of doing is a class named FlyBehavior to make an object of that type. Now let's say you have different type of ducks, like the Mallard duck, Redhead duck and now you have a Rubber duck, all of them extend the Duck class. Your rubber duck will not fly, so FlyBehavior will be different for the rubber duck. So, you make FlyBehavior an interface and create two new classes: ItFlies and NoFly, both implement the FlyBehavior interface. The constructor in Duck will have a a FlyBehavior parameter that you'll need to fill when you create a new object of type Duck, as you say, an interface can't be instantiated, but since ItFlies and NoFly, both implement the FlyBehavior interface, you can fill the FlyBehavior parameter with these two classes (or any class that implements FlyBehavior). This object oriented technique is also useful to make your program more independent and flexible in case of making modifications.
Upvotes: 1
Reputation: 4707
Actually, the explanation isn't really much different.
List animalPen = new LinkedList<>();
boolean empty = animalPen.isEmpty();
In this example, the compiler validates whether animalPen
has a method isEmpty
by looking to its reference type List
. List
declares the method isEmpty
and so, even if it does not define it, the system is then guaranteed that animalPen
has a defined method by that signature.
This is because a non-abstract class must define all methods from all interfaces it implements. This ensures that all instances of an interface is one which has, somewhere in its hierarchy, defined the interface's methods.
Upvotes: 1