8

Please look at this code:

class Sup {
    int a = 8;

    public void printA() {
        System.out.println(a);
    }

    Sup() {
        printA();
    }
}

public class Sub extends Sup {
    int a = 9;

    @Override
    public void printA() {
        System.out.println(a);
    }

    Sub() {
        printA();
    }

    public static void main(String[] args) {
        Sub sub = new Sub();
    }
}

result: console print: 0 9
I know that subclass will first calls the superclass constructor
but ,why is the 0 9 , not 8 9?

azro
  • 53,056
  • 7
  • 34
  • 70
andy.hu
  • 325
  • 1
  • 2
  • 10

1 Answers1

14

When the Sup constructor calls printA() it executes the printA method of class Sub (which overrides the method of the same name of class Sup), so it returns the value of the a variable of class Sub, which is still 0, since the instance variables of Sub are not yet initialized (they are only initialized after the Sup constructor is done).

Eran
  • 387,369
  • 54
  • 702
  • 768
  • 2
    This is also why some code standards require all methods called in constructors to be `final` or `private`. To prevent overrides causing these situations. – Kiskae Aug 16 '17 at 13:26