-3

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

 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
4

3 回答 3

2

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

static可以在不创建该类的对象的情况下调用方法。因此,如果您在静态上下文中使用此变量或非静态变量,则会产生编译错误。

于 2013-01-11T05:47:27.627 回答
0

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

public class FirstClass {

    private int idNo = 25;        

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

然后从主要方法:

FirstClass fc = new FirstClass();
fc.print();
于 2013-01-11T05:46:54.870 回答
-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();
   }
}
于 2013-01-11T05:49:13.990 回答