class CallOverriddenMethods
{
public static void main(String arg[])
{
A a = new A();
a.print();
B b = new B();
b.print();
C c = new C();
c.print();
System.out.println("-----------------");
A a1 = b; // LINE A
System.out.println("After assigning B's object to A's reference and calling the print method on A's reference");
a1.print();
System.out.println("-----------------");
B b1 = c; // LINE B
System.out.println("After assigning C's object to B's reference and calling the print method on B's reference");
b1.print();
System.out.println("-----------------");
A a2 = c; // LINE C
System.out.println("After assigning C's object to A's reference and calling the print method on C's reference");
a2.print();
System.out.println("-----------------");
}
}
class A
{
void print()
{
System.out.println("Print method in class A called");
}
}
class B extends A
{
void print()
{
System.out.println("Print method in class B called");
}
}
class C extends B
{
void print()
{
System.out.println("Print method in class C called");
}
}
Print method in class A called
Print method in class B called
Print method in class C called
-----------------
After assigning B's object to A's reference and calling the print method on A's reference
Print method in class B called
-----------------
After assigning C's object to B's reference and calling the print method on B's reference
Print method in class C called
-----------------
After assigning C's object to A's reference and calling the print method on C's reference
Print method in class C called
-----------------
Here we have created three classes - A
, B
and C
. We have implemented the same method print
in all the three classes, hence the method print is overridden in the sub-classes B
and C
. Initially we have created separate references of the same type for each object and called the print
method. We can see that the first three lines of the output shows the corresponding print statements.
But in LINE A
, we have assigned an object of B
called b
to a reference of A
called a1
. When the print method is called on the reference a1
, the print method of B
is called, since the reference is pointing to an object of type B
.
Similarly in LINE B
and LINE C
, when the sub-class object is assigned to a super-class reference and the print
method is called using that reference, it calls the method of the object type irrespective of which reference is used to call that method. So, after LINE B, the print method in class C class is called, even when B's reference is used. After LINE C, the print method in class C is called, even when A's reference is used.
D
which extends from class C
and override the method print
in it. In the main method of the class CallOverriddenMethods
, create an object of class D
and assign it to the reference of class A
. Call the print
method on the created A
's reference and observe that the print
method in class D
is called.