Run Time Polymorphism or Dynamic Binding

In this class, We discuss Run Time Polymorphism or Dynamic Binding.

The reader should have prior knowledge of compile-time polymorphism. Click Here.

First, we need to understand the below concept.

A super class variable can refer to a sub-class object.

Example:

class A

{

void m1()

{

System.out.println(“method in class A”);

}

}

Class B extends A

{

void m1()

{

System.out.println(“method in class B”);

}

}

Class C extends B

{

void m1()

{

System.out.println(“method in class C”);

}

}

Class D extends C

{

void m1()

{

System.out.println(“method in class D”);

}

}

class test

{

public static void main(String args[])

{

A ob;

ob= new A();

ob.m1();

ob=new B();

ob.m1();

ob=new C();

ob.m1();

ob=new D();

ob.m1();

B ob1=new B();

ob1.m1();

ob=ob1;

ob.m1();

}

}

The above example shows four classes A, B, C, and D.

Class B inherits A, and class C inherits B, and so on.

All classes have the same method, m1.

We created a superclass variable A ob;

The variable ob refers to the superclass A.

We can assign sub-class objects to superclass variables.

Ob = new B() assigns subclass objects to the superclass variable.

This type of object allocation is acceptable in Java.

Ob.m1() will call the method present in class B.

Similarly, we can assign any sub-class object to a superclass variable.

The next lines assign class C object. etc

The method call depends on the object assigned to the variable.

So we call this allocation run time polymorphism.

The same entity refers to different methods at different times.

The method to be called is identified during run time because objects are assigned space in execution time.

The binding of the method is done at run time. 

We call it dynamic binding.

We need to understand the naming concept.

The below example explains the concept.

class A

{

void m1()

{

System.out.println(“method in class A”);

}

void m5()

{

System.out.println(“metho m5 in class A”);

}

}

Class B extends A

{

void m1()

{

System.out.println(“method in class B”);

}

void m2()

{

System.out.println(“method m2 in class B”);

}

}

Class C extends B

{

void m1()

{

System.out.println(“method in class C”);

}

void m5()

{

System.out.println(“method m5 in class C”);

}

}

Class D extends C

{

void m1()

{

System.out.println(“method in class D”);

}

}

class test

{

public static void main(String args[])

{

A ob;

ob= new A();

ob.m1();

ob=new C();

ob.m5();

ob=new B();

ob.m2();

}

}

In the above example, we defined A ob;

ob is a reference variable belonging to class A.

ob will maintain the names of methods in class A.

ob refer to names m1 and m5.

In the program, ob is assigned a class B object.

Ob.m2() cannot execute because ob naming does not contain the name m2.