Home > Mobile >  Accessing a hidden field in a subclass
Accessing a hidden field in a subclass

Time:05-06

According to the following quote, I expect to see overriden nullstackoverflow instead of overriden nullnull. What point did I miss?

Hiding Fields

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.

class A {
    public static void main(String[] args) {
        new B("message is here");
    }

    protected int i = 13;
    public void print() { System.out.println("Hello"); }
    public A() { i = 13; print(); }
}

class B extends A {
    private String i = "stackoverflow";
    private String msg;
    public void print() { System.out.println("overriden "   msg   i); }
    public B(String msg) { super();  this.msg = msg; }
}

CodePudding user response:

What point did I miss?

The point that print() is being invoked by the A constructor, and that executes before the field initializer in B is invoked. See JLS 15.9.4 for details of exactly how class instance creation expressions execute.

So yes, it's using the B.i variable, but that variable doesn't yet have the value of stackoverflow. If you were to remove the print() invocation from the constructor and just write new B("message is here").print() then you'd see "overriden nullstackoverflow".

  • Related