2017-07-11 3 views
-2

参照することはできません与えられたコードです:私はこれらのエラーを取得しています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();

誰かが、なぜこれらを教えてくださいすることができエラーが発生しますか?

+0

を意味しましたか? – templatetypedef

+0

私はこれに答えましたが、これが単にタイプミスではない理由がない限り、それをタイプミスとしてフラグを立てるつもりです。 – Ares

答えて

0

Subは、実際にSuperを継承する必要があります。

public class Sub extends Superは、Superの変数にSubからアクセスできるようにします。

言語リファレンス:

Inheritance in Java

1

あなたの問題は、サブクラスです:

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

Super.nクラスのスコープで定義された変数にアクセスするための構文です。 Javaでは、この種の可変静的変数を呼び出します。

この問題を解決するには、次の操作を実行する必要があります。Sub`は `Super`を拡張するために`のために、あなたは

// 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); 
    } 
} 
関連する問題