1.

What is runtime polymorphism?

Answer»

Polymorphism or static polymorphism decides which method needs to be invoked at the time of compilation and bind the method invocation with the call. HOWEVER, there are some situations where the static binding doesn’t work. As we know, a parent class reference can point to a parent object as WELL as a child object. Now, if there is a method which exists in both the parent class and the child class with the same signature and we invoke the method from parent class reference, the compiler cannot decide which method to bind with the call. This will depend on which type of object the reference is pointing to at the time of running. If the reference is pointing to a parent object, then the method in the parent class will be invoked. If the pointed object is an instance of the Child class, then the child-class implementation is invoked. That’s why this is called dynamic binding or runtime polymorphism and it is said that the child class method has OVERRIDDEN the parent class method. Let’s take an example of this: class Animal { 

public void makeSound() {  System.out.println(“My sound varies based on my type”); } } class Dog extends Animal {  @Override public void makeSound() {  System.out.println(“I bark”);  } } Animal a = new Animal(); a.makeSound(); a = new Dog(); a.makeSound();

If we run the code snippet, we’ll find that a.makeSound() printing different messages based on the object-type pointed by reference. Please note that the Override annotation is REQUIRED in the child class to notify the compiler that this method is OVERRIDING the parent implementation. 



Discussion

No Comment Found