Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Vending Machine Program

 
Alex Morph
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hey first post of the forums, sorry if I break any rules!
Basically I have to create a program that will store values for 'Cans' and 'Tokens'. Simple vending machine like program, where the user inserts 2 tokens and gets 1 can.
I've only been doing java for about 3 weeks, and still trying to get my head around constructors, objects and classes etc. I'm not sure exactly how to go about writing the constructor.
I know it makes an instance of the class, but how should I write this in the code?
Thanks!

 
fred rosenberger
lowercase baba
Bartender
Posts: 12087
29
Chrome Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Constructors can be very simple. If you were to create a real live physicial vending machine, what would it's initial state be? How many cans and how many tokens would it have in it?

That's what a constructor should do - set those value to what makes sense for the initial creation.
 
Campbell Ritchie
Sheriff
Posts: 48441
56
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Welcome to the Ranch

To continue from what Fred said: you have a number of fields in your class, and the constructor must (well, at least in my opinion) set them all to sensible values. That is called establishing the class invariants.
Your method with the number of cans will almost cretahinly not do what you want it to.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic