Runtime Polymorphism or Dynamic Method Dispatch in Java

In this Java tutorial, we will learn about Dynamic Method Dispatch or Runtime Polymorphism with proper explanation and example.

Polymorphism in Java is described as performing a single task in various ways. Consider three types of a stack. One stack containing integer values, one for float values and the other for char values.
As a result, we can define a general set of a stack which will all share the same name. Therefore this is a polymorphism.

Definition of Runtime Polymorphism

In Dynamic Method Dispatch, the problem of calling an overridden method is solved during runtime.

A SIMPLE EXAMPLE:

//dynamic method dispatch
class Coffee
{
void beverage_type()
{
System.out.println("this is coffee");
}
}
class Black_coffee extends Coffee
{
void beverage_type()
{
System.out.println("this is Black coffee");
}
public static void main(String args[])
{
Coffee c=new Black_coffee();
c.beverage_type();
}
}

OUTPUT:



this is Black coffee



Hence, in this above-stated example, we can see that there are two classes Coffee and Black_coffee. Where Black_coffee class extends Coffee and the overridden method is beverage_type().
So, we created a reference variable of the parent class which is pointing to the subclass object. Hence, the subclass method overriding the parent class method. As a result, it is calling the subclass method.

You may also learn,

Java Runtime Polymorphism example

class Flights
{
void fly()
{
System.out.println("flying");
}
}
class Indigo extends Flights
{
void fly()
{
System.out.println("you are flying in Indigo");
}
}
class Goair extends Flights
{
void fly()
{
System.out.println("you are flying in Goair");
}
}
class Test
{
public static void main(String args[])
{
Flights f;
f=new Indigo();
f.fly();
f=new Goair();
f.fly();
}
}

 

OUTPUT:

you are flying in Indigo
you are flying in Goair

Rule:

  •  Only the parent class methods can override, not their data members.

A SIMPLE EXAMPLE:

class Student 
{
int no_of_students=500;
}
class Collegestudent extends Student
{
int no_of_students=250;
public static void main(String args[])
{
Student s=new Collegestudent();
System.out.println(s.no_of_students);
}
}

OUTPUT:

500

In the above-stated example, we see that both the classes have a data member no_of_students. So, we are accessing the data member by the reference variable of Parent class which refers to the subclass object.  We are accessing the data member which is not overriding. So, always it will access the data member of the Parent class.

Concept Of Class and Object in Java With Examples

Leave a Reply

Your email address will not be published. Required fields are marked *