无法从静态上下文引用非静态变量object1 [英] non-static variable object1 cannot be referenced from a static context

查看:107
本文介绍了无法从静态上下文引用非静态变量object1的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm having a little trouble getting my application to work.

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

我确实收到了错误:

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();
    }


推荐答案

您的主要方法是考虑静态,所以它只能访问静态对象,尝试声明你的object1静态:

Your "main" method is considered static and so it can only access static objects, Try declaring your object1 static:

public static Object object1;

编辑:如果你需要2个物品,这样做无害:

edit: if you need 2 objects there is no harm in doing:

public static Object object1;
public static Object object2;

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

Do not get mixed up between a static field and a static class (like a Singleton). Static in this context (static Object object1) only means that there is one and only instance of that object per instance of your class car_game, in the case above their would be 2 instance of Object (object1 and object2) even if you would instanciate 10 object of type "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是静态的所有类的实例字段属于将共享相同的实例。

it would print "this is one" because since object1 is static all instances of the class in which that fields belong will share the same instance.

这篇关于无法从静态上下文引用非静态变量object1的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆