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

前端 未结 2 1290
夕颜
夕颜 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:08

    public object object1 make this as public static object object1;

    You can not refer non-static class variables inside static method.

    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题