java非静态方法getBalance不能从静态上下文中引用 [英] java non-static method getBalance cannot be referenced from a static context

查看:365
本文介绍了java非静态方法getBalance不能从静态上下文中引用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试引用另一个类中的方法,并在我的其他类的return语句中使用它。目前,我得到的是以下错误:无法从静态上下文引用非静态方法getBalance。任何帮助将不胜感激

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 是一个实例方法。该方法的重点是它为您提供特定Account对象的余额,因此您需要一个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.

技术上调用构造函数并在新对象上调用getBalance方法,就像其他帖子显示一样,可以工作但不会给你任何有用的数据。您需要了解如何获得所需的帐户(例如通过数据库查询)。

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

您是否尝试将帐户子类化?因为bob方法看起来很像一个toString,可以在Account中看到它。如果你是子类化帐户,那么你不需要使用帐户来调用getBalance。,而是可以使用 this.getBalance() 或只是 getBalance (因为暗示)。

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

这篇关于java非静态方法getBalance不能从静态上下文中引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆