Hi guys, I searched in previous posts but could not find the satisfying answer so thought of starting a new
thread for it. I want to know what is the use of calling subclass overridden methods using superclass reference ? I mean we can directly call them using subclass references. What difference it will make ? For example check the below code.
class SuperReferenceCalling1
{
void method1()
{
System.out.println("Class SRC1");
}
}
class SuperReferenceCalling2 extends SuperReferenceCalling1
{
void method1()
{
System.out.println("Class SRC2");
}
}
class SuperReferenceCalling3 extends SuperReferenceCalling2
{
void method1()
{
System.out.println("Class SRC3");
}
}
public class SuperReferenceCalling {
public static void main(
String[] args) {
SuperReferenceCalling1 sr1 = new SuperReferenceCalling1();
SuperReferenceCalling2 sr2 = new SuperReferenceCalling2();
SuperReferenceCalling3 sr3 = new SuperReferenceCalling3();
//PartI
sr1.method1();//Line1
sr2.method1();//Line2
sr3.method1();//Line3
//PartII
sr1=sr2; //Line4
sr1.method1();//Line5
sr1=sr3; //Line7
sr1.method1();//Line8
}
}
Output :
Class SRC1
Class SRC2
Class SRC3
Class SRC2
Class SRC3
Above in main method we can see output of Line2 of PartI is same as Line4+Line5 of PartII i.e. SRC2. But I am not getting in what scenerio calling subclass method using superclass reference could be useful ?? Hope I have made my question clear. Thanks in advance.