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

编程入门 行业动态 更新时间:2024-10-09 10:30:33
本文介绍了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不能从静态上下文中引用

本文发布于:2023-11-16 03:50:14,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1600732.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:静态   文中   方法   java   getBalance

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!