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

前端 未结 3 1861
暖寄归人
暖寄归人 2021-01-15 20:30

I\'m really confused with this! I have 2 classes, Club and Membership. In Membership I have the method, getMonth(), and in

相关标签:
3条回答
  • 2021-01-15 20:35

    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.

    0 讨论(0)
  • 2021-01-15 20:42

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

    0 讨论(0)
  • 2021-01-15 20:52

    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.

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