类Java错误:无法从静态上下文引用非静态变量
以下是给定的代码:
class Super {
protected int n;
Super(int n){
this.n=n;
}
public void print(){
System.out.println("n="+n);
}
}
class Sub {
Sub(int m){
Super.n=m;
}
}
class Test{
public static void main(String[] args){
Sub s= new Sub(10);
s.print();
}
}
我发现以下错误:
Main.java:19: error: non-static variable n cannot be referenced from a static context
Super.n=m;
...........^
Main.java:25: error: cannot find symbol
s.print();
有人能告诉我为什么会发生这些错误吗
# 1 楼答案
您的问题是子类:
太好了。n是访问类作用域中定义的变量的语法。在java中,我们称这种变量为静态变量
要纠正此问题,必须执行以下操作:
# 2 楼答案
Sub
需要实际继承Super
public class Sub extends Super
将使Super的变量可以从Sub访问语言参考:
Inheritance in Java