non-static method cannot be referenced from a static context

后端 未结 5 1774
無奈伤痛
無奈伤痛 2020-12-10 09:36

I would like to understand this once and for all.

With this please excuse the mass of code pasted below, but I do not want to leave out any details.

The only

5条回答
  •  春和景丽
    2020-12-10 10:01

    If a method is not static, then it must be called "on" an object. When calling a method from a non-static method, that object is implied -- it's the object the first method was called on. But when calling it from a static method, there is no implied object, so to call the method, you must supply an object:

    GarageComm gc = new GarageComm();
    hashPos= gc.readPositions("holdingsBU.txt");
    

    Since GarageComm has no state of its own, there's no reason to create a GarageComm object, so it's just as well you mark the method static, so no object is required to call it.

提交回复
热议问题