Polymorphism ensures that the object's method is called for an object of a specific type, even when the object is declared as a more general type
Given a declaration as the following
Superclass x = new Subclass();
At compile time, x is regarded as Superclass.
At run time, x is regarded as Subclass.
Example: Consider the following classes
public class Parent
{
public void test(Parent p){
{
System.out.println("TPP");
}
public void test(Child c){
{
System.out.println("TPC");
}
}
public class Child extends Parent
{
public void test(Parent p){
{
System.out.println("TCP");
}
public void test(Child c){
{
System.out.println("TCC");
}
}
What is the output of the following codes
Parent pp = new Parent();
Parent pc = new Child();
Child cc = new Child();
pp.test(pp); //Answer: TPP
pp.test(pc); //Answer: TPP
pp.test(cc); //Answer: TPC
cc.test(pp); //Answer: TCP
cc.test(pc); //Answer: TCP
cc.test(cc); //Answer: TCC