Java Arena
Step 5 of 7

Calling the object's own methods

A method can call the other methods of its own object. Inside the class, this.isFull() calls isFull on the same object the current method was called on. This bus uses that:

Main.java
public class Main {
    public static void main(String[] args) {
        Bus bus = new Bus(2);
        bus.board();
        System.out.println(bus);
        bus.board();
        bus.board();
        System.out.println(bus);
    }
}
Bus.java
public class Bus {
    private int seats;
    private int passengers;

    public Bus(int seats) {
        this.seats = seats;
        this.passengers = 0;
    }

    public int seatsLeft() {
        return this.seats - this.passengers;
    }

    public boolean isFull() {
        return this.seatsLeft() == 0;
    }

    public void board() {
        if (this.isFull()) {
            System.out.println("Sorry, the bus is full");
        } else {
            this.passengers++;
        }
    }

    public String toString() {
        return this.passengers + " on board, seats left: " + this.seatsLeft();
    }
}
Output
1 on board, seats left: 1
Sorry, the bus is full
2 on board, seats left: 0
  • seatsLeft() works out the free seats. isFull() asks seatsLeft() instead of doing the sum again, and board() asks isFull() before it lets anyone on.
  • Each rule is written in one place. If the bus took standing passengers one day, only seatsLeft would change, and isFull, board and toString would all follow.
  • this. in front of the call can be left out: inside the class, isFull() means the same. As with instance variables, writing it shows that the method belongs to this object.

A method that only the class itself needs can be private, like the instance variables. If nothing outside the bus used seatsLeft, it could be private int seatsLeft(): isFull and toString could still call it, but main couldn't.

Your task

Challenge 1 of 3

A Flashlight knows the charge of its battery in percent, and isLow() tells whether it's below 20. Add a toString that returns the charge with a % sign, followed by (low) when the charge is low. Use isLow() for that, instead of comparing the charge again. The check prints a flashlight at 30 percent, uses 15 and prints it again:

30%
15% (low)

Challenge 2

An EggCarton holds at most 12 eggs. Add two methods. add() puts one egg in, unless the carton is full: use isFull() to check. addMany(int count) adds count eggs by calling add() that many times, so it can't overfill the carton either. The check adds 1 egg and then 8, prints the number of eggs, adds 8 more and prints it again:

9
12

Challenge 3

What does this program print? Follow each call into the class and back out.