java引用非静态库函数,java非静态方法getBalance不能从静态上下文中引用

博客内容讨论了在尝试从静态上下文调用非静态方法`getBalance`时遇到的错误。方法`getBalance`需要一个具体的`Account`实例才能调用。作者建议找到所需的`Account`对象,例如通过数据库查询,而不是直接通过类名调用。如果正在子类化`Account`,可以直接使用`this.getBalance()`或`getBalance()`。
摘要由CSDN通过智能技术生成

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 getBalance cannot be referenced from a static context. Any help would be greatly appreciated

public void bob()

{

return "Accountno.:" + super.toString() + Account.getBalance();

}

解决方案

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值