Search code examples
javafinalclass-instance-variables

Initialization of "final" instance variables


I would like to understand initialization of class instances in various cases..
In JLS-7 Section 12.5, there was no mention of how and when final instance variables were initialized? Can some one point me reference to understand the behaviour in case of instance variables declared as final?

   public class Test {

        public static void main(String args[]){

            Child  c1 = new Child();
        }
    }

    class Parent{
        final int a =30;
        Parent(){
            System.out.println("From super Contsrutor "+a);
            meth();
        }
        void meth(){
             System.out.println("From super");
        }
    }

    class Child extends Parent{
         final  int e=super.a;
         int b=30;
        void meth(){
            System.out.println("From Sub e=" +e+", b="+b);
        }
    }

is giving Output as following

From super Contsrutor 30
From Sub e=0,b=0

Where as

public class Test {

    public static void main(String args[]){

        Child  c1 = new Child();
    }
}

class Parent{
    final int a =30;
    Parent(){
        System.out.println("From super Contsrutor "+a);
        meth();
    }
    void meth(){
         System.out.println("From super");
    }
}

class Child extends Parent{
     final  int e=a;
    void meth(){
        System.out.println("From Sub " +e);
    }
}

is giving Output as

From super Contsrutor 30
From Sub 30

Solution

  • This

    final int e = a;
    

    is a constant variable, a constant expression. In the invocation

    System.out.println("From Sub e=" +e+", b="+b);
    

    the compiler can replace the use of e with its value, 30.

    In

    final int e = super.a;
    

    the variable e is not a constant variable, because super.a is not a simple name, and therefore the value cannot and will not be replaced.