I am wondering why this.(...) has no effect in this scenario. The following is a Task of my Exam:
class PARENT {
public int x;
public PARENT(int a) {this.x = a;}
public int getX() {return this.x;}
public int getY() {return this.getX();}
}
class CHILD1 extends PARENT {
public int x;
public CHILD1(int b) {super(b); this.x = 2 * b;}
}
class CHILD2 extends PARENT {
public CHILD2(int c) {super(c);}
public int getX() {return 5;}
}
public class ThisTestMain {
public static void main(String[] args) {
PARENT PP = new PARENT(10);
PARENT PC1 = new CHILD1(100);
PARENT PC2 = new CHILD2(1000);
System.out.println(PP.getY());
System.out.println(PC1.getY());
System.out.println(PC2.getY());
CHILD1 CC = new CHILD1(10);
System.out.println(CC.getY());
}
}
The output is:
10
100
5
10
My question now is why at System.out.println(PC1); the output is NOT 200. Because when I debug the code in IntelliJ I can see that this has the reference
CHILD1@799 and the Object can see the values x and PARENT.x.
At this point why is getX() choosing PARENT.x and not CHILD1.x?
By overriding methods this has also no effect. In this case for example System.out.println(PC2); uses always the getX() in CHILD2, no matter if you write in the getY() Method return this.getX(); or return getX();.
Can someone summerize the system behind that? Maybe also considering super? Thanks!
