2016-06-26 5 views
-1

前方参照メソッドを実行するときにコンパイラで発生していることは、宣言されていない別の変数の値をどのように割り当てますか?そして、私たちはその内部の方法を使うことができますか?しかし、なぜ静的ブロックで変数を使用できないのでしょうか?私たちは直接のような値を割り当てた場合たとえば、メソッド内でのみ前方参照が可能な理由

public class Forward { 

    static int i = test(); 

    static int test() { 

     System.out.println(j); 
     j = 20; 
     return j; 
    } 

    static { 
     System.out.println(j); 
     j = 20; 
    } 
    static int j; 
} 

は:

int i = j; 
int j = 10; 

なぜ、このコードはコンパイルされませんか?方法だけではどのように可能ですか?コンパイラは内部参照をどのようにコンパイルしますか?宣言はすべての変数と初期化のためにまず起こっていますか?詳細に説明してください。言い換えれば

The declaration of a class variable in a class or interface C appears textually after a use of the class variable;

、明らかに、それは「前方にする必要があります

+3

"詳細に説明" あなたは[JLS 8.8.3]を読みました(https://docs.oracle.com/javase/specs/jls /se8/html/jls-8.html#jls-8.3.3)? –

+0

あなたの投稿をありがとう。私はそれを読んだが、私は流れについての明確な画像を得ることができない。前方参照を使用する際に従わなければならない規則はありますか?それを詳しく説明できますか? – Dhivakar

答えて

1

JLS Section 8.3.3は、静的変数の将来の使用がコンパイル時にエラーと見なされる場合は4つの基準がすべて満たされなければならないと述べています宣言 ":あなたはそれを宣言する前に、あなたがそれを使用する:

// Maybe not OK to use j here. 

static int j; 

// OK to use j here. 

The use is a simple name in either a class variable initializer of C or a static initializer of C;

あなたはその名を修飾する場合は、変数への前方参照を行うことができます。

static { 
    System.out.println(j);      // Error on this line... 
    System.out.println(Forward.j);    // ...but not this line... 
    System.out.println(org.whatever.Forward.j); // ...or this line... 
} 
static int j; 

この基準は、可変または静的初期設定子にのみ適用されます。これは、メソッドの静的変数を参照するときにコンパイルエラーが発生しない理由の特定の質問に答えます。あなたは順序を逆にしても、変数を割り当てる除いて何もできない

static { 
    System.out.println(j); // Error on this line... 
    j = 20;     // ...but not this line. 
} 
static int j; 

しかし、このコードで

The use is not on the left hand side of an assignment;

が注...ちょうど物事を終えるましょう(あなたはそれを割り当ててから印刷することはできません)。

C is the innermost class or interface enclosing the use.

次のコードは、罰金のようになります。

class Forward { 
    static class Inner { 
    static { 
     System.out.println(j); 
    } 
    } 

    static int j; 
} 
関連する問題