有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

类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();

有人能告诉我为什么会发生这些错误吗


共 (2) 个答案

  1. # 1 楼答案

    您的问题是子类:

    class Sub {
        Sub(int m){
            Super.n=m; // <- this line of code!
        }
    }
    

    太好了。n是访问类作用域中定义的变量的语法。在java中,我们称这种变量为静态变量

    要纠正此问题,必须执行以下操作:

    // With the extends Super, you are inheriting properies and methods
    // from Super class
    class Sub extends Super {
        Sub(int m){
            // Now you are calling a constructor from the parent             
            super(m);
        }
    }
    
  2. # 2 楼答案

    Sub需要实际继承Super

    public class Sub extends Super将使Super的变量可以从Sub访问

    语言参考:

    Inheritance in Java