2015-04-01 152 views
0

我试图访问一个INT = 10变量子类,但得到的错误:如何访问子类中的父类整数变量?

Cannot make a static reference to the non-static field FreshJuice.a

以下是我的代码。

class FreshJuice { 
    enum FreshJuiceSize{SMALL,MEDIUM,LARGE}; 
    FreshJuiceSize size; 
    int a = 10; 
} 

public class Index extends FreshJuice { 

    enum programmingLanguage{PHP,Java,Dotnet,HTML}; 

    public static void main(String[] args) { 
     // TODO Auto-generated method stub 

     System.out.println(FreshJuice.FreshJuiceSize.SMALL); 
     System.out.println(programmingLanguage.PHP); 
     System.out.println(FreshJuice.a); //getting error in this line 
    } 

} 

我想直接访问子类中的FreshJuice类的int变量。我怎样才能达到这个目标?

+1

你为什么抽象而隐秘?你有错误。准确告诉我们**你得到了什么错误。但是,在你这样做之前,检查其他人是否有同样的错误。 (提示:他们有。) – 2015-04-01 15:49:11

+0

你需要一个类的实例。这不是静态的。 – Ria 2015-04-01 15:54:27

+0

我收到错误无法对非静态字段FreshJuice.a进行静态引用 – Jass 2015-04-01 15:58:25

回答

0

首先创建FreshJuice类的一个实例:

FreshJuice fj = new FreshJuice();

现在你可以访问变量a

但是,如果您将变量设置为private int a=10;那么您仍然无法访问该变量。这就是为什么使用getter和setter方法访问这些私有变量是很好的做法。