i have just started learning java::Inheritance and confused while mixing Up-Casting.
class Example{
public void methodOne(){
System.out.println("Example::Method_1");
}
public void methodTwo(){
System.out.println("Example::Method_2");
}
}
public class Test extends Example{
public void methodTwo(){ //Method overriding
System.out.println("Test::Method_2");
}
public void methodThree(){
System.out.println("Test::Method_3");
}
public static void main(String[] args){
Example exa = new Test(); // UpCasting
exa.methodOne(); // Printing Example::Method_1
exa.methodTwo(); // Printing Test::Method_2
// exa.methodThree(); // Error : can not find symbol
}
}
may someone please explain, what happening here??
When using inheritance, the compile-time type of the reference to an object on which you call a method is only used to see (at compile time) if the method may be invoked.
But at the invocation time, it does not matter what that compile-time type is. What really matters in this case is the runtime type of the object. It is Test, so the method is searched on Test first.
For methodOne() it is a bit different: it is not overriden by Test, so the version from its superclass (Example) is invoked.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With