In the below code snippet, the result is really confusing.
public class TestInheritance {
public static void main(String[] args) {
new Son();
Polymorphic method invocations apply only to instance methods. You can always refer to an object with a more general reference variable type ( a superclass or interface ), but at runtime, the ONLY things that are dynamically selected based on the actual object (rather than the reference type) are instance methods NOT STATIC METHODS. NOT VARIABLES. Only overridden instance methods are dynamically invoked based on the real object’s type.
So variable x
has not polymorphic behaviour because IT WILL NOT BE SELECTED DYNAMICALLY AT RUNTIME.
Explaining your code :
System.out.println(this);
The Object type is Son
so toString()
method's Overridden Son
version will be invoked.
System.out.println(this.x);
Object type is not in picture here, this.x
is in Father
class so x
variable's Father
version will be printed.
See more at: Polymorphism in java