2017-07-27 89 views
2

我用下面的代碼段,這給了我一個錯誤的點指示:靜態嵌套類與非靜態錯誤?

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.

+8

如果沒有static關鍵字,pair就會變成LinkedList的內部類,這意味着每個'pair'對象都必須和封閉'LinkedList'類的實例關聯。 – Eran

回答

3

在情況1中,pairLinkedList成員。這意味着您只能通過LinkedList訪問對,而不能直接訪問該對的任何變量或方法。

A nested class is a member of its enclosing class. Non-static nested classes (inner classes) have access to other members of the enclosing class, even if they are declared private. Static nested classes do not have access to other members of the enclosing class.

要實例化一個內部類,必須首先實例化外部類。然後,創建外部對象內的內對象與此語法:

OuterClass.InnerClass innerObject = outerObject.new InnerClass(); 

然而,在情況2中,一對就像任何其他頂層類,只是分組以維持的關係。它根本不是外部階級的成員。你可以直接訪問它。

Note: A static nested class interacts with the instance members of its outer class (and other classes) just like any other top-level class. In effect, a static nested class is behaviorally a top-level class that has been nested in another top-level class for packaging convenience.