1
在下面的代碼中,爲什麼Java認爲簡單名稱numCows
可能未被初始化?爲什麼使用限定符 - 這可以防止錯誤?Qualified在簡單的名字在匿名類
import java.util.function.Function;
public class CowFarm {
private final int numCows;
public CowFarm(int numCows) {
this.numCows = numCows;
}
// Fails to compile
//
// CowFarm.java:12: error: variable numCows might not have been initialized
public final Function<Integer, Integer> MULTIPLY_COWS = (k -> numCows * 2);
// Works fine
public final Function<Integer, Integer> DIVIDE_COWS = (k -> CowFarm.this.numCows * 2);
}