Pravin yadav
Pravin yadav

Reputation: 707

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

Upvotes: 0

Views: 122

Answers (3)

Lµk4s
Lµk4s

Reputation: 66

If you change your constructor to

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

and set a debug point to super(); you will see that the constructor gets called before the init(1);. It just gets called before your System.out.println("Inside Constructor");.

You can also write:

public class Test {
    final int i;

    Test(){
        super();
        i = init(1);
        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);

    }
}

Upvotes: 2

This behaviour in the code is correct and has nothing to do with your analysis about the final key word...

init(1); is a method that is getting called as soon the class is constructing an instance...

there fore all inside the method will be executed even before the constructor...

Upvotes: 1

M Sach
M Sach

Reputation: 34424

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?

Upvotes: 3

Related Questions