Polymorphism is briefly described as “one interface, many implementations”. Polymorphism is a characteristic of being able to assign a different meaning or usage to something in different contexts – specifically, to allow an entity such as a variable, a function, or an object to have more than one form. There are two types of polymorphism:
- Compile time polymorphism
- Run time polymorphism
Compile time polymorphism is method overloading whereas Runtime time polymorphism is done using inheritance and interface.
Runtime Polymorphism :
In Java, runtime polymorphism or dynamic method dispatch is a process in which a call to an overridden method is resolved at runtime rather than at compile-time. In this process, an overridden method is called through the reference variable of a superclass. Let’s take a look at the example below to understand it better.
class Car {void run(){System.out.println(“car is running”); }}class Audi extends Car {void run(){System.out.prinltn(“Audi is running safely with 100km”);}public static void main(String args[]){Car b= new Audi(); //upcastingb.run();}} |