I try to understand with inheritance in Java . There is some code:
class A { A getThis() { System.out.println("call getThis() from A"); return this; //(3) } //(3) Object getSuper() { System.out.println("call getSuper() from A"); return null;} } class B extends A { B getThis() { System.out.println("call getThis() from B"); return this; } A getSuper() { System.out.println("call getSuper() from B"); return super.getThis(); } } class Tester { public static void main (String[] args) { Object a = new B().getSuper(); //(1) System.out.println(a); a = new B().getSuper().getSuper(); //(2) System.out.println(a); } } As a result, the following text is output to the console:
call getSuper () from B
call getThis () from A
B @ 25154f
call getSuper () from B
call getThis () from A
call getSuper () from B
call getThis () from A
B @ 10dea4e
I expected that when working out line (1) in a will be an instance of class A , and after working out line (2) in a will be null . Why does the return of this from line (3) return the link not to the parent class, but to the original one?
As I understand it, when creating an instance of class B , it stores a reference to an instance of the parent class A I see indirect confirmation of my words:
When a class B constructor is called, the class A constructor is called. Even by redefining the method f in class B, one can get to the method f class A through the construction super.f() ;
Despite this, when working with an instance of class B , I see no way to return from it a reference to an instance of class A , which is used in it. Is there any way to realize this opportunity?
A a = new B()? - GrundyA a = new B();It is also not an answer to the question, since we are only performing an upward transformation. By referenceawill still be an instance of classBEven when callingaf();the call to the overridden method, but not the base method, will work. - Roxio0