2017-07-27 67 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.