Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
365 views
in Technique[技术] by (71.8m points)

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

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();
   }
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...