Chapter 4 - Java for Beginners Course

Example Project - A Simple Vending Machine

For the code example in this chapter, we’ll assume we’re programming a very simple vending machine.

Our simple vending machine has the following properties:

  1. Sells only one type of product with a fixed cost of 10.

  2. Will deliver an item only if there is enough balance.

  3. Customers can add money to the vending machine.

  4. Customers can request change if available.

  5. The vending machine has an unlimited supply of items to deliver (for simplicity purposes!).

  6. The maximum balance it can hold is 100.

The basics of our UnlimitedSupplyVendingMachine class

The version of the UnlimitedSupplyVendingMachine class in the example project in GitHub is the final version you’ll get after following these sections. You can use that one as reference if you’re following these sections step-by-step.
public class UnlimitedSupplyVendingMachine {
    private int maxAllowedBalance = 100;

    private int costPerItem = 10;

    private int balance = 0;

    public int getBalance() {
        return balance;

Our basic UnlimitedSupplyVendingMachine class above allows us to query the current balance the customer has. Now, let’s implement the other features of our vending machine.

We’ll continue adding functionality to our UnlimitedSupplyVendingMachine class in the next sections to illustrate more concepts that we covered in the first 3 chapters.
For those of you that know about static constants, you’ll notice that we’re not using them in this example. Main reason here is that we haven’t introduced that concept yet in our beginners course. We’ll start using them later when we cover the static keyword.