无法从静态上下文引用非静态变量object1

我在申请上class时遇到了一些麻烦。

我得到error: error: non-static variable object1 cannot be referenced from a static context

我确实得到了错误:

 error: object_game is not abstract and does not override abstract method keyPressed(KeyEvent) in KeyListener public class car_game extends JFrame implements Runnable, KeyListener 

但我修复了因为我需要keyTyped, keyPressed, keyReleased定义。

这是我的代码:

 public class car_game extends JFrame implements Runnable, KeyListener { public object object1; //Main program public static void main(String[] args) { object1 = new Object() {}; Thread t = new Thread(new object_game()); t.start(); } 

您的“main”方法被认为是静态的,因此它只能访问静态对象,请尝试声明object1 static:

 public static Object object1; 

编辑:如果你需要2个对象,那么做是没有害处的:

 public static Object object1; public static Object object2; 

不要在静态字段和静态类(如Singleton)之间混淆。 此上下文中的静态(静态Object object1)仅表示每个类car_game的实例中只有该对象的一个​​实例,在上面的情况下,它们将是Object的两个实例(object1和object2),即使您将实例化10 “car_game”类型的对象。

例如,如果我这样做:

 car_game carGameObject1 = new car_game(); car_game carGameObject2 = new car_game(); carGameObject1.setObject1("this is one"); 

然后:

 System.out.println(carGameObject2.getObject1()); 

它会打印“this is one”,因为因为object1是静态的,所以该字段所属的类的所有实例将共享同一个实例。

public object object1将其设为public static object object1;

您不能在静态方法中引用非静态类变量。