Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

Analyzing some weird scenarios in following static block :

static {
  System.out.println("Inside Static Block");
  i=100; // Compilation Successful , why ?
  System.out.println(i); // Compilation error "Cannot reference a field before it is defined"
}

private static int i=100;

While same code is working fine while using :

static {
  System.out.println("Inside Static Block");
  i=100; // Compilation Successful , why ?
  System.out.println(MyClass.i); // Compiles OK
}

private static int i=100;

Not sure why variable initialization do not need variable access using class name while SOP requires ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
126 views
Welcome To Ask or Share your Answers For Others

1 Answer

This is because of the restrictions on the use of Fields during Initialization. In particular, the use of static fields inside a static initialization block before the line on which they are declared can only be on the left hand side of an expression (i.e. an assignment), unless they are fully qualified (in your case MyClass.i).

So for example: if you insert int j = i; right after i = 100; you would get the same error.

The obvious way to solve the issue is to declare static int i; before the static initialization block.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...