Java Arena
Step 5 of 6

Changing an object

An object remembers. Its instance variables keep their values from one method call to the next, and a method can change them. The values an object holds at a given moment are its state. Here the plant gets two methods that change its height:

Main.java
public class Main {
    public static void main(String[] args) {
        Plant ivy = new Plant("ivy", 40);
        ivy.printInfo();
        ivy.grow(15);
        ivy.printInfo();
        ivy.cut(30);
        ivy.printInfo();
        ivy.cut(50);
        ivy.printInfo();
    }
}
Plant.java
public class Plant {
    private String name;
    private int height;

    public Plant(String name, int height) {
        this.name = name;
        this.height = height;
    }

    public void printInfo() {
        System.out.println(this.name + ", " + this.height + " cm");
    }

    public void grow(int cm) {
        this.height = this.height + cm;
    }

    public void cut(int cm) {
        this.height = this.height - cm;
        if (this.height < 5) {
            this.height = 5;
        }
    }
}
Output
ivy, 40 cm
ivy, 55 cm
ivy, 25 cm
ivy, 5 cm
  • this.height = this.height + cm; changes the object's own height. After ivy.grow(15) it stays 55 until another call changes it, and the next printInfo() prints the new value. (this.height += cm; does the same.)
  • cut has a condition. The gardener always leaves at least 5 cm, so a plant never gets shorter than that: ivy.cut(50) would take the height to -25, and the if puts it back up to 5.
  • Some methods change the state, like grow and cut. Others only look at it, like printInfo.

A method that changes the state doesn't need a parameter. The lamp's turnOn() from step 1 simply sets this.on = true;.

Your task

Challenge 1 of 3

The WaterBottle from step 3 comes full and has a printInfo() method. Add a method drink(int amount) that takes amount milliliters out of the bottle. A bottle can't hold less than nothing: when the amount is more than what's left, the bottle becomes empty (0 ml). The check runs:

WaterBottle bottle = new WaterBottle(750);
bottle.drink(200);
bottle.printInfo();
bottle.drink(600);
bottle.printInfo();

and expects:

550/750 ml
0/750 ml

Challenge 2

A TrafficLight shows red, green or yellow. Its constructor, which has no parameters, starts it at red. Write the method next(), which moves the light on: red turns green, green turns yellow, and yellow turns red again. The check runs:

TrafficLight light = new TrafficLight();
light.printColor();
light.next();
light.printColor();
light.next();
light.printColor();

and expects:

red
green
yellow

Challenge 3

What does this program print? The elevator remembers its floor between the calls.