Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Static Instance Variable Lookup Java [duplicate]

class A {int x = 5;}
class B extends A {int x = 10;}
class D {
    public static void main(String[] args){
        A b0 = new B();
        System.out.print(b0.x);
    }
}

I am wondering why this code prints 5 instead of 10.

If I instead write the following, converting the variables x to methods, it works more as I'd expect, and prints out 10, since at compile time it merely checked if b0's static type, A, has a method x, and then at runtime, uses b0's dynamic type, B, to run x.

class A {int x() {return 5;}}
class B extends A {int x() {return 10;}}
class D {
    public static void main(String[] args){
        A b0 = new B();
        System.out.print(b0.x());
    }
}

My theory is that instance variables are looked up statically unlike methods, but I am not sure about why that would be.

Thanks!

like image 223
FLOWMEEN Avatar asked Nov 02 '15 09:11

FLOWMEEN


1 Answers

In B the field x from A is shadowed(hidden) not overriden. To answer "why that would be" references to the docs here and here. The compiler will pick one of the 2 instances of x according to the type of the containing object. And b0 is of type A

 A b0 = new B();

When you define (getter) methods on the other hand these can override methods with the same signature in the parent class. Another nasty surprise is that a field in the parent class is shadowed even if it's a different type.

Shadowing of members is considered a bad practice as it tends to confuse developers.

like image 146
Manos Nikolaidis Avatar answered Oct 16 '22 15:10

Manos Nikolaidis