2

次のコードがあるとします。

public class A {
 static final long tooth = 1L;

 static long tooth(long tooth){
  System.out.println(++tooth);
  return ++tooth;
 }

 public static void main(String args[]){
  System.out.println(tooth);
  final long tooth = 2L;
  new A().tooth(tooth);
  System.out.println(tooth);
 }
}

シャドーイングの概念を教えてください。toothもう1つ、メインメソッドのコードで実際に使用されているものは何ですか?

そして、それが非常に醜いコードであることは知っていますが、SCJP の本の著者にとって醜いコードは標準的な選択です。

4

2 に答える 2

2

概念としてのシャドーイングには魔法のようなものは何もありません。名前への参照は、常に最も近い外側のスコープ内のインスタンスを参照するだけです。あなたの例では:

public class A {
 static final long tooth#1 = 1L;

 static long tooth#2(long tooth#3){
  System.out.println(++tooth#3);
  return ++tooth#3;
 }

 public static void main(String args[]){
  System.out.println(tooth#1);
  final long tooth#4 = 2L;
  new A().tooth#2(tooth#4);
  System.out.println(tooth#4);
}

}

「tooth#N」の形式で、各インスタンスに番号を付けました。基本的に、他の場所ですでに定義されている名前を導入すると、そのスコープの残りの部分の以前の定義が無効になります。

于 2010-07-21T15:18:09.313 に答える
1

この時点で

System.out.println(tooth);

クラス プロパティ ( static final long tooth = 1L;) が使用され、クラス プロパティをシャドウする newtoothが宣言されます。これは、クラス プロパティの代わりに使用されることを意味します。

toothメソッド内では、tooth変数が値として渡され、変更されません。これを実行すると、次のようmainになります。

1
3
2
于 2010-07-21T15:21:41.110 に答える