Non-static method (method name()) cannot be referenced from a static context. Why?

不打扰是莪最后的温柔 提交于 2019-12-01 12:19:49

Membership is a class. Calling methods though it is only allowed if the method is static. Your getMonth method isn't static, so you will need an instance of the Membership class to call it. You already have a list of instances in your Club class, so pick one of those and call getMonth on it.

Static modifier make method/field to be part of class not object (instance). You call it by using class name as reference (or object reference, but that is bad practice). If method/field is not static it must to be called via reference to class object (instance).

Static method can be accessed using the class name. In the above code, you are trying to access getMonth() method with class name Membership (Membership.getMonth()). But the signature of the getMonth() is public int getMonth(){ ... }, Here this method doesn't contain any static keyword. Because of this you are getting "non-static method getMonth() cannot be referenced from a static context".

To solve this we should change public int getMonth() to public static int getMonth() or use the object which you created already for Membership class.

Hope this is helpful.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!