Search code examples
javainterfacepolymorphism

How does dynamic polymorphism in java apply to interfaces?


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.


Solution

  • 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.