2015-05-29 78 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();