Notes
The problem
Imagine a ride app written with no classes. Plates live in one array and free seats in another, and cab number one means index one in every array. Book three riders twice and the seat count goes to minus two, because nothing checks it. Add a driver name and you need a third array. Sort the plates and the seats silently stop matching. The data and the rules about the data are scattered everywhere.
String[] plates = {"KA01", "KA02"};
int[] freeSeats = {4, 4};
// book cab 1: same index everywhere
freeSeats[1] -= 3;
freeSeats[1] -= 3; // now -2 !
// add "driver": a third array
// sort plates: seats no longer match The idea
Here is the idea in one sentence. A class describes a kind of thing: what it knows and what it can do. An object is one real instance of that class, with its own values. Cab is the class, the blueprint. The cab with plate K A zero one is an object. You write the class once, and the program creates as many objects as it needs while it runs.
- a class describes a kind of
- thing: what it knows and
- what it can do
- an object is one instance
- of that class, with its
- own values
- class Cab: the blueprint
- cab KA01: one real cab
State and behaviour
A class has two parts. State is the data each object carries, stored in fields: the plate, the capacity and the free seats. Behaviour is what the object can do, written as methods: board some riders, drop everyone off, report free seats. The key move is that the rule about seats now lives in one place, inside the board method, right next to the data it protects.
final class Cab {
private final String plate; // state
private final int capacity;
private int freeSeats;
// behaviour
void board(int riders) { ... }
void dropAll() { ... }
int freeSeats() { return freeSeats; }
} Constructors
A constructor is the special block that runs exactly once when an object is created. Its job is to make the object valid from its very first moment. Our cab constructor rejects a blank plate and a capacity of zero or less, then sets every field. The word this means the object being built. If a constructor can never produce a broken object, the rest of the code never has to wonder.
Cab(String plate, int capacity) {
if (plate == null || plate.isBlank())
throw new IllegalArgumentException();
if (capacity <= 0)
throw new IllegalArgumentException();
this.plate = plate;
this.capacity = capacity;
this.freeSeats = capacity;
} Instances
The new keyword asks Java to build an object from the class. It reserves memory on the heap, runs the constructor and hands back a reference. Here we create two cabs: K A zero one with four seats and K A zero two with six. Each object has its own copy of every instance field, so boarding riders into the first cab does not change the second cab at all.
References
A variable of a class type does not hold the object. It holds a reference, like an address. When we write alias equals first, no new cab is made. Both names now point to the same object, so boarding one rider through alias also changes what first reports. This surprises many beginners, and it matters later when we talk about sharing objects and defensive copies.
Cab first = new Cab("KA01", 4);
Cab alias = first; // no new object
alias.board(1);
first.freeSeats(); // also changed
assigning copies the reference,
not the cab Static vs instance
Most fields are instance fields: every cab has its own plate. A static field is different. It belongs to the class itself, and there is only one copy, shared by every object. Our cab class keeps a static counter of how many cabs were created. A static method, like created, is called on the class name and has no this, so it cannot touch instance fields directly.
private static int created = 0;
Cab(...) { ...; created++; }
static int created() { return created; }
Cab.created() // 2, no object needed
not thread safe: use AtomicInteger
if many threads create cabs When to use static
Use static for things that are true for the whole class: constants like a maximum seat count, pure helper functions like Math dot max, and named factory methods. Avoid static for changing shared data, like a static list of every booking. That is a global variable in disguise. It is hard to test, hard to reset between tests and impossible to swap for a fake. Interviewers notice static-heavy designs quickly.
- good:
- constants: MAX_SEATS
- pure helpers: Math.max
- factory methods: Cab.of(...)
- bad:
- mutable global state
- "manager" classes full of
- static methods and data
- (hard to test, hard to swap)
Identity vs equality
Two kinds of sameness. Identity asks: are these the very same object in memory? That is what the double equals operator checks. Equality asks: do these two objects mean the same thing? That is the equals method. By default, equals only checks identity, so two cab objects with the same plate are not equal. If your design says a plate identifies a cab, you override equals to compare plates.
Cab a = new Cab("KA01", 4);
Cab b = new Cab("KA01", 4);
a == b // false: two objects
a.equals(b) // false by default!
default equals = identity
override it to say what
"the same cab" means: same plate equals and hashCode
Override equals and you must override hashCode too, using the same fields. The rule is: if two objects are equal, they must return the same hash code. Hash sets and hash maps first jump to a bucket by hash code, then compare with equals. Break the rule and a hash set happily stores two copies of the same cab. Also base the hash on fields that never change, like the final plate, or the object gets lost inside the set.
@Override
public boolean equals(Object o) {
return o instanceof Cab other
&& plate.equals(other.plate);
}
@Override
public int hashCode() {
return plate.hashCode();
}
// equal objects: equal hash codes Run-through
Let us trace the demo. The ride app calls new cab with plate K A zero one. The constructor checks the inputs, sets the fields and bumps the shared counter. The app boards three riders, and the cab itself checks the seats. Later a second object with the same plate is added to the fleet set. Because equals and hashCode compare plates, the set sees a duplicate and keeps only one.
Records
Since Java sixteen, a record is a short way to declare a class that just carries data. For a fare with a city and an amount, the record gives you final fields, a constructor, accessor methods, and equals, hashCode and toString based on all the fields. You can still add a compact constructor to validate. Use records for values like a fare or a location, and normal classes for things with changing state, like a cab.
record Fare(String city, int rupees) {
Fare {
if (rupees < 0)
throw new IllegalArgumentException();
}
}
// final fields, constructor, accessors,
// equals, hashCode, toString: generated In interviews
In a design round, start from the nouns in the problem: cab, rider, trip, fare. They become classes. The verbs, like book, cancel and pay, become methods on the class that owns the data. Common mistakes are classes that only hold getters and setters while all the logic sits in one giant manager, public fields anyone can change, equals without hashCode, and static lists used as a fake database.
- • classes with only getters
- and setters, logic elsewhere
- • one giant "Manager" class
- • public mutable fields
- • equals without hashCode
- • static lists as a database
- in a parking lot or a ride
- app: nouns become classes,
- verbs become methods