1.

What is run-time polymorphism and how it is achieved in Java?

Answer»
  • Run-time polymorphism(dynamic binding or dynamic method dispatch) implies that the call to an overridden method is RESOLVED dynamically during run-time instead of compile-time.
  • Run-time polymorphism is achieved with the help of method overriding in Java. When a child class(subclass) has the same method name, return type, and parameters as the parent(superclass), then that method overrides the superclass method, this process is known as method overriding.
    Example:
    The below example has one superclass ANIMAL and three subclasses, Birds, Mammals, and Reptiles. Subclasses extend the superclass and override its PRINT() method. We will call the print() method with the help of the reference variable of Animal class i.e., parent class. The subclass method is invoked during runtime since it is referring to the object of the subclass and the subclass method overrides the superclass method. As Java Virtual Machine(JVM) decides method invocation, it is run-time polymorphism.
class Animal{ void print(){ System.out.println("Inside Animal"); } } class Birds extends Animal{ void print(){ System.out.println("Inside Birds"); } }class Mammals extends Animal{ void print(){System.out.println("Inside Mammals");} }class Reptiles extends Animal{ void print(){ System.out.println("Inside Reptiles"); } }class InterviewBit{ public STATIC void main(String args[]){ Animal a = new Animal(); Animal b = new Birds(); //upcasting Animal m = new Mammals(); //upcasting Animal R = new Reptiles(); //upcasting a.print(); b.print(); m.print(); r.print(); } }

Output:

Inside AnimalInside BirdsInside MammalsInside Reptiles


Discussion

No Comment Found