Part 2 of 7 · 1 min read
Class and object
The class is the plan, the object is the thing built from it.
A house plan is not a house. Many houses can be built from one plan, and each has its own paint and its own owner. A class is the plan, and an object is one house built from it.
GoF explains that the class decides how an object is built: which data it keeps inside and which operations it can carry out. Creating an object from a class is called instantiating it, and the object is an instance of the class. Many instances can come from one class, each with its own data.
class Room {
private final String id;
private final int capacity;
Room(String id, int capacity) {
this.id = id;
this.capacity = capacity;
}
boolean fits(int people) {
return people <= capacity;
}
}
Using it: Room small = new Room("R1", 4); and Room large = new Room("R2", 20); make two objects from one class. small.fits(6) is false and large.fits(6) is true. The class is written once, and the objects differ only in their data.
Class and object
A class defines the data and operations of a kind of thing. An object is one instance of that class, holding its own data.
Example: Room is a class. The room "R1" with capacity 4 is an object.
Check yourself:
1. How many classes and how many objects are in the two-room example?
2. Which of the two holds the data of "R1"?
3. What does new do?