Java inheritance fields

dhS :

I am not able to understand the following output.

I don't know why the output is 10, I think the line A a = new B() creates a new instance of class B, I think the result should be 20

class A {
    int i = 10;
}

class B extends A {
    int i = 20;
}

public class MainClass {
    public static void main(String[] args) {
        A a = new B();

        System.out.println(a.i);
    }
}

Why this works like this .. please explain.

cricket_007 :

First, see Hiding Fields (emphasis added)

Within a class, a field that has the same name as a field in the superclass hides the superclass's field, even if their types are different

In other words, this isn't "inheritance" since you're actually hiding A's i behind B's i, and you are using a reference object of A, so you are getting its fields. If you did B b = new B(), you would see 20, as expected.


If you expect true overrides, try using methods.

class A {
    public int get() { 
        return 10; 
    }
}

class B extends A {
    @Override 
    public int get() { 
        return 20; 
    }
}

See

A a = new B();
System.out.print(a.get()); // 20

If you really want to see both at once, see this example.

class A {
    int i = 10;
}

class B extends A {
    int i = 20;

    @Override 
    public String toString() { 
        return String.format("super: %d; this: %d", super.i, this.i);
    }
}

And

A a = new B();
System.out.print(a); // super: 10; this: 20

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=426825&siteId=1