Initializing a final variable in a method called from class constructor

Alireza :

Today I'm facing a strange behavior which I couldn't figure out why.

Imagine we have a final variable in a typical class in Java. We can initialize it instantly or in class constructor like this:

public class MyClass {

    private final int foo;

    public MyClass() {
        foo = 0;
    }
}

But I don't know why we can't call a method in constructor and initialize foo in that method, like this:

public class MyClass {

    private final int foo;

    public MyClass() {
        bar();
    }

    void bar(){
        foo = 0;
    }
}

Because I think we are still in constructor flow and it doesn't finished yet. Any hint will be warmly appreciated.

Elliott Frisch :

First, assigning the value at declaration time is copied into every constructor for you by the compiler. Second, you can use a method to initialize the value, but you need to return it for that to work. As others' note, you are required to ensure this value is set once.

public class MyClass {
    private final int foo = bar();

    private static int bar() {
        return 0;
    }
}

Which is equivalent to

public class MyClass {
    private final int foo;

    public MyClass() {
        this.foo = bar();
    }

    private static int bar() {
        return 0;
    }
}

Note that bar is static, because otherwise you need an instance to call it.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=465583&siteId=1