0

I read that instance variables of the child class get initialized after constructor of the super class. So why initialize() in class B prints 0, but not an error that symbol f1 not found? And why it prints 0, but not 3?

public class Test {
    
    public static void main(String[] args) {
        new B();
    }

    public static class A {
        
        public static int f1 = 7;

        public A() {
            initialize(); // I know that should not use method in the constructor
        }

        protected void initialize() {
            System.out.println(f1);
        }
    }

    public static class B extends A {
        
        public int f1 = 3;

        public B() {}

        protected void initialize() {
            System.out.println(f1); // why 0 but not an error: can not resolve symbol f1
        }
    }
}
flaxel
  • 3,429
  • 4
  • 13
  • 26
Denis_newbie
  • 1,128
  • 4
  • 13
  • Well, the compiler can resolve the symbol, so it is not a case for a "cannot resolve symbol" compiler error. The field is just not initialized yet (because initializers get executed **after** super-constructors). – Hulk Sep 21 '20 at 12:21
  • You only get a "cannot resolve symbol" error when the compiler can't resolve the symbol. – khelwood Sep 21 '20 at 12:23

0 Answers0