Search code examples
javainitializationfinalsuperclass

final vairable initialization relative to super class constructor


As this (Initialize field before super constructor runs?) post states, all non static variables get initialized after the super class constructor runs, but in the following example, while debugging I see that the variable isn't initialized before the parent constructor runs, the print function prints the result "B=5" as if it was initialized.

When I use a non final variable the result is "B=0" as expected.

What's going on?

here is the code:

public class A {
    int a=77;
    public A(int i){
        printMe();
    }

    public void printMe(){
        System.out.println("A "+a);
    }
}

public class B extends A{
    //static int a=5; //test  will print 5
    final int a=5; //test  will print 5
    //int a=5;         ////test will print 0
    public B() {
        super(0);
    }

    public void printMe(){
        System.out.println("B="+a);
    }

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

Solution

  • This

    final int a=5;
    

    is a constant variable, which is a constant expression. The compiler will replace all references to it with its value.

    So

    System.out.println("B="+a);
    

    will actually compile to

    System.out.println("B="+5); // B=5