中級 › 値が変わらないときに疑う変数の隠蔽 › パターン4
値が変わらないときに疑う変数の隠蔽
同名のローカル変数がフィールドを覆い隠します。
1 public class Main { 2 int total = 100; 3 void addAll(int[] nums) { 4 __________total = 0; ^ 5 for (int n : nums) total += n; 6 } 7 public static void main(String[] args) { 8 Main m = new Main(); 9 m.addAll(new int[]{1, 2, 3}); 10 System.out.println(m.total); 11 } 12 }
出力: 100期待: 6 (コンパイルは通っています)
空欄を埋めてビルドを通す
型を書くとローカル変数total が新しく作られ、フィールドのtotalは別物のまま変わりません。
次の問題