javafinal

Assigning final keyword using a method


I was just playing with final keyword and observed the below behavior, here i am assigning a final variable using a method and the method is getting called before the constructor

 public class Test {

    final int i=init(1);

    Test(){
        System.out.println("Inside Constructor");
    }

    public int init(int i){
        System.out.println("Inside Method");
        return i;
    }

    public static void main(String [] args){
        Test i=new Test();
        System.out.println(i.i);

    }

The Output of the following code is as below

Inside Method
Inside Constructor
1

I know final variable needs to be assigned before the constructors completes and this is what is happening here

What i am unable to find is that how can a method be called before a constructor, i really appreciate any explanation for this


Solution

  • It has nothing to do with finalkeyword. Try below(just removed final ) output will be same. Basically instance variable will be initialized first then constructor is called

    public class Test {
         int i = init(1);
    
        Test() {
            System.out.println("Inside Constructor");
        }
    
        public int init(int i) {
            System.out.println("Inside Method");
            return i;
        }
    
        public static void main(String[] args) {
            System.out.println("start");
            Test i = new Test();
            System.out.println(i.i);
        }
    }
    

    Now why and how instance variable get initialized before constructor see Why instance variables get initialized before constructor called?