The following program demonstrates the run time polymorphism.
class RunTimePolymorphism
{
public static void main(String arg[])
{
int input = 24;
A aref;
if(input < 10)
{
aref = new A();
}
else if(input < 30)
{
aref = new B();
}
else
{
aref = new C();
}
aref.print(); // LINE A
}
}
class A
{
void print()
{
System.out.println("class A method called.");
}
}
class B extends A
{
void print()
{
System.out.println("class B method called.");
}
}
class C extends A
{
void print()
{
System.out.println("class C method called.");
}
}
OUTPUTclass B method called.
DESCRIPTIONHere we have created 3 classes - B
extends from A
, C
also extends from A
. In the main
method, we have created a variable called input
. Then depending upon the value of input
, we have either created an object of A
or B
or C
and assigned it to the reference of A
called aref
. At LINE A
, we are only calling the print
method using aref
.
Although here, input
is initialized to 24
, it is not necessary that it will be always 24
. It could be different if we have taken the input value from user during run-time. The user could give 5
or 20
or 35
as the input. Since the input
value decides which object will be created and assigned to aref
, the method which will be called is also decided at run-time.
THINGS TO TRY
- Try the below code.
B ref = new A();
The above line of code gives a Compilation Error. We can assign a sub class object to super class reference but we can not assign a super class object to a sub class reference.