I am learning about method overriding in Java. Below is an example of method overriding.
class ABC{
public void myMethod(){
System.out.println("Overridden Method");
}
}
public class XYZ extends ABC{
public void myMethod(){
System.out.println("Overriding Method");
}
public static void main(String args[]){
ABC obj = new XYZ();
obj.myMethod();
}
}
When an overridden method is called through a reference of parent class, then type of the object determines which method is to be executed. Now consider below :
ABC obj = new ABC();
obj.myMethod();
// This would call the myMethod() of parent class ABC (1)
XYZ obj = new XYZ();
obj.myMethod();
// This would call the myMethod() of child class XYZ (2)
ABC obj = new XYZ();
obj.myMethod();
// This would call the myMethod() of child class XYZ (3)
If (2) and (3) gives same output : Overriding Method, then why use (3)? We could just use (2) right?
I am new to Java, so I will tend to ask many doubts! Please help! Thank you!