我用下面的代碼段,這給了我一個錯誤的點指示:靜態嵌套類與非靜態錯誤?
class LinkedList{
class pair{
Integer petrol;
Integer distance;
public pair (Integer a, Integer b){
petrol = a;
distance = b;
}
}
public static void main(String args[]){
pair[] circle = {new pair(4,6), new pair(6,5), new pair(7,3), new pair(4,5)}; // error at first element of array circle!!!!!!!
}
}
我那麼糾正這個和錯誤dissapeared!
class LinkedList{
static class pair{ // changed to static!!!
Integer petrol;
Integer distance;
public pair (Integer a, Integer b){
petrol = a;
distance = b;
}
}
public static void main(String args[]){
pair[] circle = {new pair(4,6), new pair(6,5), new pair(7,3), new pair(4,5)}; //error gone!
}
}
我的問題是爲什麼錯誤甚至出現在第一位呢?
ERROR: No enclosing instance of type LinkedList is accessible. Must qualify the allocation with an enclosing instance of type LinkedList.
如果沒有static關鍵字,pair就會變成LinkedList的內部類,這意味着每個'pair'對象都必須和封閉'LinkedList'類的實例關聯。 – Eran