Polymorphism in Java

Polymorphism in Java is a concept by which a single action can be performed in different ways. Polymorphism is derived from 2 Greek words: poly and morphs. The word "poly" means many and "morphs" means forms. Therefore, polymorphism means many forms.

Polymorphism is the capability of a method to do different things based on the object that it is acting upon. In other words, polymorphism allows you define one interface and have multiple implementations. 

There are two types of polymorphism in Java: compile-time polymorphism and runtime polymorphism(dynamic polymorphism). We can perform polymorphism in java by method overloading and method overriding.

If you overload a static method in Java, it is the example of compile time polymorphism. Here, we will focus on runtime polymorphism in java.

Example of Java Runtime Polymorphism

In this example, we are creating two classes Car and Toyota. Toyota class extends Car class and overrides its run() method. We are calling the run method by the reference variable of Parent class. Since it refers to the subclass object and subclass method overrides the Parent class method, the subclass method is invoked at runtime.

Since method invocation is determined by the JVM not compiler, it is known as runtime polymorphism.

class Car{  

  void run( ) {   System.out.println("running");  }  

}  

class Toyata extends Car{  

  void run( ) {  System.out.println("running safely with 80km");  }  

  

  public static void main(String args[]){  

    Car b = new Toyota( );  //Overriding  

    b.run( );  

  }  

}