Just adding to what marc said
getString() is ovveriden and getGreeting() is not ovverriden
A a = new A();
B b = new B();
a.greeting() will invoke the greeting() that is defined in the object pointed by reference a which is class A object and hence a.getgreeting() will invoke greeting() of class A
Same applies to a.getName()
With same reasoning as above b.greeting() will invoke the greeting() that is defined in class B, But class B does not have greeting() or does it have, Since class B extends A , greeting() is inherited by class B but since it doesnt override it , greeting() of class A is invoked. However if greeting() were to be declared private in class A then class B would not have inherited it and b.greeting() will result in a compilation error.
b.getName() This will invoke the overriden method in class B because class B overrides it and reference "b" refers to class B object at runtime.
Overriden is defined only for instance methods.
Just for information
Here
Here any access to varaibles of class PArent or class Child are resolved at compile time and not at runtime as in case of instance methods. Hence
Hence p.parent in System.out.println("p.parent:"+p.parent); will display the value of parent in class Parent, which is expected.
And c.parent in System.out.println("c.parent:"+c.parent);
will display the value of parent in class Child, which is expected.
But if i assign parent class reference to child object [
polymorphism]
"p = c;" then System.out.println("p.parent:"+p.parent); will again refer
to the parent value in Parent class and not the one defined in Child class. This is because the access to variables is determined at compile time.
Hope this helps
Thanks
Deepak