Unit 09 · lesson
An Object Should Represent a Coherent Concept
Suppose a program tracks a competition team using separate variables:
int teamNumber = 2180;
String teamName = "Zero Gravity";
int wins = 3;
int losses = 2;
Those values belong to one domain concept: a team.
A class can make that relationship explicit.
class Team {
int number;
String name;
int wins;
int losses;
}
Create an object:
Team team = new Team();
team.number = 2180;
team.name = "Zero Gravity";
team.wins = 3;
team.losses = 2;
This is only the beginning. Publicly mutable fields do not yet protect the model, but we have created a coherent boundary.
Class versus object
The class describes a type and its structure/behavior.
An object is a runtime instance.
Team class
|
| new Team()
v
specific Team object
Multiple objects can exist from the same class:
Team a = new Team();
Team b = new Team();
They can hold different state.
Behavior belongs where the knowledge lives
Add:
int matchesPlayed() {
return wins + losses;
}
The method depends on Team state and represents a team behavior/calculation, so it belongs naturally inside the class.
Do not turn every program into a giant Utility class with methods that manipulate unrelated data from the outside.
References change assignment reasoning
Two references can identify one mutable object
Assigning an object reference does not automatically clone the object.
- OBJECTone runtime instance owns mutable statereferenced by
- REFERENCE Avariable A identifies the objectassign to B
- REFERENCE Bvariable B identifies the same objectmutate
- SHARED STATEthe single object changesobserve
- SAME OBJECTboth references reveal updated state
With primitive values:
int a = 5;
int b = a;
a = 9;
b still contains 5.
With object references:
Team a = new Team();
a.wins = 3;
Team b = a;
b.wins = 10;
IO.println(a.wins);
Both variables refer to the same object, so the observed wins through a is now 10.
Do not say "the whole object was copied" unless your evidence actually supports a separate object.
Identity versus state
Two different Team objects could contain the same field values and still be distinct objects.
That distinction matters when deciding equality rules later.
Model a concept
Choose one:
StudentAttempt;RobotRun;GameMatch;SensorReading;BookLoan.
Define:
- state that belongs together;
- one behavior calculated from that state;
- one piece of data that does not belong in the object;
- whether the concept should have meaningful identity over time.
Implement a class and create at least two separate objects.
Evidence
Draw a reference/object diagram for your two objects. Then create one aliasing experiment where two variables refer to the same object and explain the resulting state change.
Object-oriented reasoning begins when you can distinguish the name of a reference from the object it identifies.