• Post Reply Bookmark Topic Watch Topic
  • New Topic

Trying to learn classes.  RSS feed

 
Justice Smith
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Here I am again. Trying to create this first class (Bank Account), then use it in class (Tester). It tells me it can't recognize variable "balance" when I try to compile class Tester.





I don't know what I'm doing wrong, but it says it can't recognize the variable "balance" in the second set of code.
 
Paweł Baczyński
Bartender
Posts: 2074
44
Firefox Browser IntelliJ IDE Java Linux Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It is because there is no variable balance in your Tester class.
If you want to print the balance of your account use myAccount.balance.
 
Amruta nikam
Greenhorn
Posts: 22
Chrome Eclipse IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Justice Smith wrote:Here I am again. Trying to create this first class (Bank Account), then use it in class (Tester). It tells me it can't recognize variable "balance" when I try to compile class Tester.





I don't know what I'm doing wrong, but it says it can't recognize the variable "balance" in the second set of code.


Hi use myAccount.balance instead of balance inside system.out.println

however its not the way to access variables.... read about getters and setters...so whenever outside the class you are trying to access or chnage the value of any variable you should access it through getters and chnage it by using setters
google it you can find so many tutorials on it...

and you are getting that error because you are trying to access non static variable inside static method(here main())
 
Justice Smith
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks to both of you, got it fixed!
 
Campbell Ritchie
Marshal
Posts: 56518
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
How did you fix it?
SW is right to say to use getter methods. I would probably not use set methods in a bank class myself, only deposit and withdraw methods. The balance field should be private.
There is a temptation to fix “non‑static” compiler errors by marking things static. That might sort out the compiler error, but usually makes the design much worse.
 
Consider Paul's rocket mass heater.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!