错误:无法从静态上下文引用非静态变量

时间:2013-01-11 05:41:28

标签: java compiler-errors

我从教科书中得到了这段代码。

 class FirstClass
 {
     int idNo =25;
     public static void print()
     {
         System.out.println("firstclass citizen " + idNo);
     }
 }
 class SecondClass
 {
     int idNo =24;
     public static void print()
     {
         System.out.println("secondclass citizen" + idNo);
     }
 }
 public class People
 {
     //FirstClass female;
     //SecondClass male;
     public static void main(String[] args)
     {
         System.out.println("people from java world");
         FirstClass.print();
         SecondClass.print();
     }
 }

但是在编译这段代码时我遇到了以下错误

People.java:7: error: non-static variable idNo cannot be referenced from a stati
c context
            System.out.println("firstclass citizen " + idNo);
                                                       ^
People.java:16: error: non-static variable idNo cannot be referenced from a stat
ic context
            System.out.println("secondclass citizen" + idNo);
                                                       ^
2 errors

3 个答案:

答案 0 :(得分:2)

this引用当前的Object,您可以使用它来引用实例方法或构造函数中的当前对象的任何成员。 但您不能在静态上下文(方法或块)中使用this引用

可以在不创建该类的对象的情况下调用

static方法。因此,如果将此静态变量或非静态变量用于静态上下文,则会产生编译错误。

答案 1 :(得分:0)

您可能想要创建类的实例,并将方法转换为实例方法而不是静态方法。

public class FirstClass {

    private int idNo = 25;        

    public void print() {
        System.out.println("firstclass citizen " + this.idNo);
    }
}

然后从主方法:

FirstClass fc = new FirstClass();
fc.print();

答案 2 :(得分:-1)

您不能引用非静态属性并将其用于静态方法,即

class FirstClass
{
    static int idNo =25;
    public static void print()
    {
            System.out.println("firstclass citizen " + idNo);
    }
}
class SecondClass
{
    static int idNo =24;
    public static void print()
    {
            System.out.println("secondclass citizen" + idNo);
    }
}
public class People
{
    FirstClass female;
    SecondClass male;
    public static void main(String[] args)
    {
            System.out.println("people from java world");
            FirstClass.print();
            SecondClass.print();
   }
}