To expand upon what Elliot was saying.
Your interface that returns true if the coin was accepted.
public interface Coinable {
public boolean insertCoin();
}
Some person class that has some coins to insert into a Coinable
interface.
public class Person {
private int coins;
public Person(int coins) {
this.coins = coins;
}
public void insertCoin(Coinable cn) {
if (this.coins <= 0) {
System.out.println("You have no coins");
} else {
boolean coinAccepted = cn.insertCoin();
if (coinAccepted) {
coins--;
}
}
}
}
And your GumballMachine that implements the Coinable interface.
class GumballMachine implements Coinable {
private int gumBalls;
public GumballMachine(int gumBalls) {
this.gumBalls = gumBalls;
}
@Override
public boolean insertCoin() {
if (gumBalls <= 0) {
System.out.println("There are no gumballs left");
return false;
} else {
System.out.println("A gumball was dispensed!");
gumBalls--;
return true;
}
}
}
And an example of how all this works
public static void main(String[] args) {
Person p = new Person(3); // 3 coins
GumballMachine g = new GumballMachine(2); // 2 gumballs
p.insertCoin(g);
p.insertCoin(g);
p.insertCoin(g); // out of gumballs
g = new GumballMachine(2); // refill the machine, still have 1 coin
p.insertCoin(g);
p.insertCoin(g);
}
Output
A gumball was dispensed!
A gumball was dispensed!
There are no gumballs left
A gumball was dispensed!
You have no coins