Java で前方参照を使用していますが、なぜ Java がClassName
(静的変数で) またはthis
インスタンス変数の場合の参照で前方参照を許可するのか疑問に思っています。JVM のレベルで行われているバックグラウンド プロセスは何ですか? 例えば:
静的前方参照 -
class StaticForwardReferences {
static {
sf1 = 10; // (1)
int b = sf1 = 20; // (2)
int c = StaticForwardReferences.sf1; // (3) Works fine
// Above statement allows the allocation of value of 'sf1'
// to variable 'c' just because it is accessed with class name
// instead of direct name
// whereas below statement throws illegal forward reference
// error at compile time
System.out.println(sf1); // (4) Illegal forward reference
}
static int sf1 = sf2 = 30;
static int sf2;
public static void main(String[] args) {}
}
上記の(1)および(2)の手順で行ったように、宣言の前に変数を割り当てて前方参照を行うときに値が格納される一時的なストレージはありますか? variable の値を出力すると、値がc
表示されます最近の割り当てから にしましたsf1
。
非静的前方参照-
class NonStaticForwardReferences {
{
nsf1 = 10;
System.out.println(this.nsf1); // 10
nsf1 = sf1;
// System.out.println(nsf1); Illegal forward reference
int b = nsf1 = 20;
int c = this.nsf1;
System.out.println(c); // 20
// why variable 'c' is initialized to 20 when used with 'this' reference
// instead of showing illegal forward reference, how it works in the background?
}
int nsf1 = nsf2 = 30;
int nsf2;
static int sf1 = 5;
public static void main(String[] args) {}
}
上記の 2 つのケースについて、舞台裏で行われているバックグラウンド プロセスに光を当ててください。前もって感謝します!:)