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:
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();
}
}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;
}
}
}ivy, 40 cm
ivy, 55 cm
ivy, 25 cm
ivy, 5 cmthis.height = this.height + cm;changes the object's own height. Afterivy.grow(15)it stays 55 until another call changes it, and the nextprintInfo()prints the new value. (this.height += cm;does the same.)cuthas 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 theifputs it back up to 5.- Some methods change the state, like
growandcut. Others only look at it, likeprintInfo.
A method that changes the state doesn't need a parameter. The lamp's turnOn() from step 1 simply sets this.on = true;.