Home » Java » inheritance – Why does this.<variable> or this.<method()> in Parent Class have no effect? Java-Exceptionshub

inheritance – Why does this.<variable> or this.<method()> in Parent Class have no effect? Java-Exceptionshub

Posted by: admin February 23, 2020 Leave a comment

Questions:

I am wondering why this.(…) has no effect in this scenario. I tried to make this as simple as possible:

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
[email protected] 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!

Debug in IntelliJ

How to&Answers:

In CHILD1 you have no overridden methods.

So when you call getY() it then calls getX() from the PARENT. The method from the PARENT has no idea about variables in its child classes.

You must override method getX() in CHILD1 to get access to the variable CHILD1.x.

Answer:

CHILD1 defines a new field named x that shadows the field x in PARENT. Remove the field. Like

class CHILD1 extends PARENT {
    // public int x;
    public CHILD1(int b) {super(b); this.x = 2 * b;}
}