Initialization of the final variable in the method called from the class constructor

Today I came across strange behavior that I could not understand why.

Imagine we have a final variable in a typical Java class. We can initialize it immediately or in the constructor of the class as follows:

public class MyClass {

    private final int foo;

    public MyClass() {
        foo = 0;
    }
}

But I do not know why we cannot call the method in the constructor and initialize fooin this method, for example:

public class MyClass {

    private final int foo;

    public MyClass() {
        bar();
    }

    void bar(){
        foo = 0;
    }
}

Because I think that we are still in the constructor stream, and it is not finished yet. Any hints would be much appreciated.

+4
source share
3 answers

-, . -, , return . , , .

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

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

public class MyClass {
    private final int foo;

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

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

, bar - static, .

+7

. :

  • .

:

class Program {
static final int i1 = 10;
static final int i2;
static {
    i2 = 10;
}

}

, , , :

class Program {
final int i1 = 10;
final int i2;
final int i3;
{
    i2 = 10;
}

Program() {
    i3 = 10;
}

}

. .

class Program {
void method() {
     final int i1 = 10;
     final int i2;
     System.out.println(i1);
     i2 = 10;
     System.out.println(i2);
     return ;
}

}

:

+2

( ) , , :

  • , , , .
  • .

:

  • .
  • .

, , -. ( ), javac , . :

  • -, . , , , . , .
  • , . , , , . , ( ) . - - , . javac , , - - . , .
  • . , , , ( ) .
  • , , , . , factory. , , .

, . , , . , .

0

Source: https://habr.com/ru/post/1694773/


All Articles