non-static variable object1 cannot be referenced from a static context

前端 未结 2 1291
夕颜
夕颜 2021-01-29 09:43

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

I get the error: error: non-static variable object1 cannot be referenced from a static context

2条回答
  •  南方客
    南方客 (楼主)
    2021-01-29 10:22

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

    public static Object object1;
    

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

    public static Object object1;
    public static Object object2;
    

    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".

    For example if i'd do:

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

    And then:

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

    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.

提交回复
热议问题