Runtime polymorphism, also known as Dynamic Method Dispatch, is the process through which a call to an overridden method is resolved at runtime rather than compile-time. The method includes using a superclass's reference variable to invoke an overridden method.The method to be called will be determined by the object to which the reference variable refers.
Runtime polymorphism offers a significant advantage by allowing a class to provide its specific implementation to an inherited method. This implementation transfer from one method to another can be carried out without modifying the parent class object's codes. Additionally, a call to a method that has been overridden can be resolved dynamically while in use.
Upcasting is the practise of referencing an object from a child class in a reference variable of the parent class.
Syntax
class A{}
class B extendsA{}
A a= new B();//upcasting
In the example below, two classes Car and Nano are being created. The run() method of the Car class is overridden by the Nano class. Using the Parent class's reference variable, we are invoking the run method. The subclass method is called at runtime because it makes reference to the subclass object and overrides the parent class method.Runtime polymorphism refers to the fact that the JVM, not the compiler, decides which method to invoke.
// Java Run-Time Polymorphism example
class car { int speedlimit = 25; void run() { System.out.println("Runnning at 25 kmph speed"); } } class Nano extends car { int speedlimit = 35; void run() { System.out.println("Runnning at 35 kmph speed"); } public static void main(String args[]) { car obj = new Nano(); //upcasting System.out.println(obj.speedlimit); obj.run(); } }
Output:
25 // run time polymorphism achive
Runnning at 35 kmph speed
class Father{ void eat(){ System.out.println("Father Eating"); } } class Daughter extends Father{ void eat(){ System.out.println("Daughter Eating"); } } class Son extends Father{ void eat(){ System.out.println("Son Eating"); } } class DockerTpoint{ public static void main(String args[]){ Father father,father2,father3; father=new Father(); father.eat(); father2=new Daughter(); father2.eat(); father3=new Son(); father3.eat(); } }
Output:
Father Eating
Daughter Eating
Son Eating
class Shape{ void draw(){ System.out.println("Drawing "); } } class Rectangle extends Shape{ void draw(){ System.out.println("Rectangle"); } } class Circle extends Shape{ void draw(){ System.out.println("Circle "); } } class Triangle extends Shape{ void draw(){ System.out.println("Triangle"); } } class Square extends Shape{ void draw(){ System.out.println("Square"); } } class DockerTpoint{ public static void main(String args[]){ Shape shape; shape=new Rectangle(); shape.draw(); shape=new Circle(); shape.draw(); shape=new Triangle(); shape.draw(); shape=new Square(); shape.draw(); } }
Output:
Rectangle
Circle
Triangle
Square
Post your comment