如果类动物是嵌套在测试时,我得到的错误:嵌套类在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);
}
}
在此先感谢您。