2015-05-29 64 views
2

如果類動物是嵌套在測試時,我得到的錯誤:嵌套類在Java和引用它們的靜態主

"non-static variable this cannot be referenced from a static context"

能否請您解釋一下這個錯誤,並提供一種方法,使此代碼的工作,同時仍然保持嵌套類?我想學習使用嵌套類並更好地理解它們。

錯誤就行創建A1時出現:Animal a1 = new Animal();

PS:當動物是一個獨立的階級(不嵌套)類,測試類之外,代碼的工作,但我感興趣的嵌套類。

public class Test { 
    class Animal { 
     String colour; 

     void setColour(String x) { 
      colour = x; 
     } 
     String getColour() { 
      return colour; 
     } 
    } 
    public static void main(String[] args) {   
     Animal a1 = new Animal(); 
     Animal a2 = a1; 
     a1.setColour("blue"); 
     a2.setColour("green"); 
     System.out.println(a1.colour); 
     System.out.println(a2.colour); 
    } 
} 

在此先感謝您。

回答

2

可以使動物類的靜態和使代碼工作。

否則,如果你不使內部類(動物)靜態。內部類(Animal)的對象只能與外部類(Test)的實例一起存在。所以,如果你不想讓它變成靜態的,你必須先創建一個Test實例才能創建一個Animal實例。

例如

Animal a1 = new Test().new Animal(); 

請參閱https://docs.oracle.com/javase/tutorial/java/javaOO/nested.html以獲得更好的理解。

3

,使其與嵌套類工作,申報Animalstatic類:

public class Test { 
    static class Animal { 
     String colour; 

     void setColour(String x) { 
      colour = x; 
     } 
     String getColour() { 
      return colour; 
     } 
    } 
    public static void main(String[] args) {   
     Animal a1 = new Animal(); 
     Animal a2 = a1; 
     a1.setColour("blue"); 
     a2.setColour("green"); 
     System.out.println(a1.colour); 
     System.out.println(a2.colour); 
    } 
} 

而要了解它爲什麼沒有工作之前,有Nested Classes documentation的讀取。關鍵是大概:

An instance of InnerClass can exist only within an instance of OuterClass and has direct access to the methods and fields of its enclosing instance.

3

Animal是一個內部類的Test,這意味着它的任何實例必須與封閉類型Test的實例相關聯。

如果您希望使用Animal作爲常規類實例化它與new Animal()而不需要Test一個實例,將其更改爲static,你的主要方法會奏效。

2

正如其他人說你可以使用靜態嵌套類通過測試實例從靜態上下文引用,或實例化的動物,像下面這樣:

new Test().new Animal();