Initializing Static Finite Fields in Java

public class Main {
 static final int alex=getc();
 static final int alex1=Integer.parseInt("10");
 static final int alex2=getc();

public static int getc(){
    return alex1;
}

public static void main(String[] args) {
    final Main m = new Main();
    System.out.println(alex+" "+alex1 +" "+alex2);
  } 
}

Can someone tell me why this prints 0 10 10:? I understand that this is a static final variable and its value should not change, but it’s a little difficult to understand how the compiler initializes the fields.

+5
source share
5 answers

This situation is covered by JLS 8.3.2.3 "Restrictions on the use of fields during initialization".

JLS rules allow use in your Question and indicate that the first call getc()will return the default value (uninitialized) alex.

; .

int i = j + 1;
int j = i + 1;

.


. , Java " ". Java. (, , , . , , Java- , , Java .)


:

... .

.

final:

  • " " . ( " String, " - . JLS 4.12.4.). , ... , .

  • final , JLS, . final , ( a static) .


, " ". final .

+3

. , , , getc() alex, alex1 . alex1, .

+6

, , . , alex , alex1 , getc() alex1 (0).

, (10 10 10) :

static final int alex1 = 10;

alex1 , .

+4

, , , , .

.

public class Main {
    private final int a;

    public Main() {
        System.out.println("Before a=10, a="+getA());
        this.a = 10;
        System.out.println("After a=10, a="+getA());
    }

    public int getA() {
        return a;
    }

    public static void main(String... args) {
        new Main();
    }
}

Before a=10, a=0
After a=10, a=10
+2

, . (, int, short...), 0 () Object it null. alex1 0. , .

For a better explanation, read http://download.oracle.com/javase/tutorial/java/javaOO/classvars.html

0
source

All Articles