Several objects
One class can make as many objects as a program needs, and each object keeps its own state: calling a method on one of them never changes the others. The values for new objects often come from the user:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("First plant:");
String first = scanner.nextLine();
System.out.println("Second plant:");
String second = scanner.nextLine();
Plant left = new Plant(first, 10);
Plant right = new Plant(second, 10);
left.grow(8);
right.grow(3);
left.cut(12);
left.printInfo();
right.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;
}
}
}mint
basilFirst plant:
Second plant:
mint, 6 cm
basil, 13 cmleftandrightare built from the same class, with names read from the user, and each has its ownnameandheight.left.grow(8)andleft.cut(12)change onlyleft: the variable in front of the dot decides which object a method works on.rightonly grew by 3.
A program can use as many classes as it needs, each in its own file next to Main.java, and main can make objects of all of them: a garden program could have a Plant class and a Lamp class, and create a few of each. Module 19 shows how to keep any number of objects in a list.