java non-static method getBalance cannot be referenced from a static context

后端 未结 4 1841
北荒
北荒 2020-12-11 13:25

I\'m trying to refer to a method in another class and use that in a return statement in my other class. At the moment, all I get is the following error: non-static method ge

相关标签:
4条回答
  • 2020-12-11 13:46

    The proper way of doing it is having a instance of Account , account and call

    Account account = new Account();
    account.getBalance(); 
    

    or declare your metho getBalance as static.

    0 讨论(0)
  • 2020-12-11 13:52

    You must have an object instance for calling getBalance(). You are calling like a static mehod. This should work:

    Account acc = new Account();
    acc.getBalance();
    
    0 讨论(0)
  • 2020-12-11 13:52

    You're trying to call a non-static method as if it were static. Assuming that you have a class Account, Account.getBalance() would only work for a static getBalance() method. You need an instance of Account in order to call a non-static getBalance() method.

    0 讨论(0)
  • 2020-12-11 13:53

    getBalance is an instance method. The point of the method is it gives you the balance for a specific Account object, so you you need an instance of Account in order to call getBalance on it. When you call a method prefaced by the class name, that's what is meant by 'static context', it means you're calling a static method on the class.

    Technically calling the constructor and calling the getBalance method on the new object, like the other posts show, will work but won't give you any useful data. You need to find out how to get the Account that you want (such as through a database query).

    Are you trying to subclass Account? Because the bob method looks a lot like a toString that would look at home in Account. If you are subclassing the Account then you don't need to preface the call to getBalance with Account., instead you can use this.getBalance() or just getBalance (because this is implied).

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