Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java instance variable resolution in Java is confusing;

Tags:

java

I am studying for my OCA exam and came across this problem and It is very confusing.

Variable resolution always based on reference type instead of the runtime object. So if my parent and child class look like this:

class Parent {

    public int x = 1;

    public int getX() {
        return x;
    }
}

class Child extends Parent {
    public int x = 2;

    public int getX() {
        return x;
    }
}

Based on the rules (variable resolution is always based on reference type), the following code is behaving as expected:

    Child c = new Child();
    System.out.println(c.x);                    //2
    System.out.println(((Parent) c).x);         //1

However. if I retrieve the variables by using the getter defined in the parent and child class, then I get this:

    Child c = new Child();
    System.out.println(c.getX());               //2
    System.out.println(((Parent) c).getX());    //2

Shouldn't it print the same as if I was to access the variable directly? why would getting the variable via getter be different than getting the variable directly?

One theory I have is this:

Since instance method resolution is based on runtime object, therefore it overrides the variable resolution rule. In other words, the compiler will resolve the getter methods to the child class since instance method resolution is based on runtime object. Am I right?

Thank you

like image 772
Brendon Cheung Avatar asked Oct 18 '25 09:10

Brendon Cheung


1 Answers

Methods and variables behave differently. Variables do not get inherited or participate in polymorphism.

The Parent and Child classes each have their own distinct variable x. One doesn't override the other. You can use the cast to specify that you want the Parent's x, not the Child's.

With the method, it doesn't matter what cast you stick on it, when calling the Child you get the overridden version of getX. (Within a method of the Child you can call super.getX to get the parent's version of the method.)

TLDR: variable resolution rules don't apply to methods. Polmorphism doesn't apply to variables.

like image 159
Nathan Hughes Avatar answered Oct 19 '25 22:10

Nathan Hughes



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!