LOW-LEVEL DESIGN · OBJECT-ORIENTED PROGRAMMING · FOUNDATIONS · 1 OF 48

Classes and Objects in Java: State, Behaviour and Instances

What a class and an object really are, shown with a small ride app: state and behaviour kept together, constructors that make every object valid from birth, many instances from one blueprint, references, static versus instance members, and the basics of equals and hashCode, with a runnable Java 17 example.

  1. 1
  2. 2
  3. 3
  4. 4
  5. 5
  6. 6
  7. 7
  8. 8
  9. 9
  10. 10
  11. 11
  12. 12
  13. 13
  14. 14
  15. 15
  16. 16
  17. 17
  18. 18
  19. 19
  20. 20
  21. 21
  22. 22
  23. 23
  24. 24
  25. 25
  26. 26
  27. 27
  28. 28
  29. 29
  30. 30
  31. 31
  32. 32
  33. 33
  34. 34
  35. 35
  36. 36
  37. 37
  38. 38
  39. 39
  40. 40
  41. 41
  42. 42
  43. 43
  44. 44
  45. 45
  46. 46
  47. 47
  48. 48
1 / 15

Press play to hear the narration, or step through at your own pace. The Java example is below.

Java example

One file, Java 17, 143 lines, with a small main() demo. Save it as ClassesAndObjectsDemo.java, then run javac ClassesAndObjectsDemo.java && java ClassesAndObjectsDemo.

import java.util.HashSet;
import java.util.Set;

/**
 * Classes and objects, shown with a tiny ride app.
 * Part 1: the problem. Cab data is spread over loose arrays and nothing protects it.
 * Part 2: the clean version. A Cab class keeps its state and the rules about that state together.
 */
public class ClassesAndObjectsDemo {

    // ---------- Part 1: the problem (no class, just parallel arrays) ----------
    static void withoutClasses() {
        String[] plates = {"KA01", "KA02"};
        int[] freeSeats = {4, 4};
        // "Cab 1" means index 1 in every array. Nothing checks the values.
        freeSeats[1] -= 3;
        freeSeats[1] -= 3;
        System.out.println("Arrays: " + plates[1] + " has " + freeSeats[1] + " free seats (broken!)");
    }

    // ---------- Part 2: the clean version ----------
    public static void main(String[] args) {
        withoutClasses();

        // Two objects built from one class. Each has its own fields.
        Cab first = new Cab("KA01", 4);
        Cab second = new Cab("KA02", 6);
        first.board(3);
        System.out.println(first);
        System.out.println(second);

        // Static member: one counter for the whole class, read through the class name.
        System.out.println("Cabs created so far: " + Cab.created());

        // References: alias points to the SAME object as first.
        Cab alias = first;
        alias.board(1);
        System.out.println("first after alias boards one rider: " + first.freeSeats() + " free");

        // The object guards its own rule, so the arrays bug cannot happen.
        try {
            first.board(2);
        } catch (IllegalStateException e) {
            System.out.println("Rejected: " + e.getMessage());
        }

        // Identity vs equality.
        Cab sameCarAgain = new Cab("KA01", 4);
        System.out.println("first == sameCarAgain      : " + (first == sameCarAgain));
        System.out.println("first.equals(sameCarAgain) : " + first.equals(sameCarAgain));

        // equals + hashCode together let a HashSet spot the duplicate.
        Set<Cab> fleet = new HashSet<>();
        fleet.add(first);
        fleet.add(second);
        fleet.add(sameCarAgain);
        System.out.println("Unique cabs in the fleet: " + fleet.size());

        // A record: a small immutable value with equals/hashCode/toString generated.
        Fare a = new Fare("Pune", 180);
        Fare b = new Fare("Pune", 180);
        System.out.println(a + " equals " + b + " ? " + a.equals(b));
    }
}

/** The blueprint. State (fields) and behaviour (methods) live together. */
final class Cab {
    // static: ONE copy, shared by every Cab. (Use AtomicInteger if many threads create cabs.)
    private static int created = 0;

    // instance state: every Cab object has its own copy of these.
    private final String plate;
    private final int capacity;
    private int freeSeats;

    /** Runs once per object and makes it valid from the very first moment. */
    Cab(String plate, int capacity) {
        if (plate == null || plate.isBlank()) {
            throw new IllegalArgumentException("plate is required");
        }
        if (capacity <= 0) {
            throw new IllegalArgumentException("capacity must be positive");
        }
        this.plate = plate;
        this.capacity = capacity;
        this.freeSeats = capacity;
        created++;
    }

    /** Behaviour: the seat rule lives next to the seat data. */
    void board(int riders) {
        if (riders <= 0) {
            throw new IllegalArgumentException("riders must be positive");
        }
        if (riders > freeSeats) {
            throw new IllegalStateException(plate + " has only " + freeSeats + " free seats");
        }
        freeSeats -= riders;
    }

    void dropAll() {
        freeSeats = capacity;
    }

    int freeSeats() {
        return freeSeats;
    }

    String plate() {
        return plate;
    }

    /** Static method: called on the class, has no "this". */
    static int created() {
        return created;
    }

    /** Two Cab objects mean the same cab when the plate matches. */
    @Override
    public boolean equals(Object o) {
        return o instanceof Cab other && plate.equals(other.plate);
    }

    /** Same field as equals, and a field that never changes. */
    @Override
    public int hashCode() {
        return plate.hashCode();
    }

    @Override
    public String toString() {
        return "Cab " + plate + " (" + freeSeats + " of " + capacity + " seats free)";
    }
}

/** A record: final fields, constructor, accessors, equals, hashCode and toString for free. */
record Fare(String city, int rupees) {
    Fare {
        if (rupees < 0) {
            throw new IllegalArgumentException("fare cannot be negative");
        }
    }
}

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.

Cabs without a class
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.

In one sentence
  • 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.

class Cab
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.

Constructor
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.

Two names, one object
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.

static
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 and bad static
  • 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.

Same cab or equal cab?
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.

The contract
@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.

Java record
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.

Common mistakes
  • • 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

Interview questions

What is the difference between a class and an object?

A class is a definition: it declares the fields and methods a kind of thing has. An object is a single instance created from that class at runtime, with its own values for the instance fields. One class can produce any number of objects.

What does a constructor do, and how is it different from a method?

A constructor runs once when an object is created and sets it up in a valid state. It has the same name as the class and no return type, and it is called through new rather than on an existing object. A method runs on an object that already exists.

What is the difference between static and instance members?

Instance fields and methods belong to each object, so every object has its own copy of the fields. Static members belong to the class and have a single shared copy. A static method has no this reference, so it cannot use instance fields without an object.

What is the difference between == and equals() in Java?

The double equals operator compares references for objects, so it is true only when both sides point to the same object. The equals method compares logical equality as defined by the class. The default equals in Object behaves like double equals until a class overrides it.

Why must you override hashCode when you override equals?

The contract says equal objects must have equal hash codes. Hash based collections use the hash code to find the bucket before calling equals, so if two equal objects hash differently, a HashSet can store duplicates and a HashMap lookup can miss an existing key.

What happens when you assign one object variable to another?

Only the reference is copied, so both variables point to the same object. A change made through one variable is visible through the other. To get an independent object you must create a new one or make a copy.

When would you use a record instead of a class?

Use a record for a simple, immutable data carrier such as a money amount or a coordinate. Java generates the constructor, accessors, equals, hashCode and toString from the components. Use a regular class when the object has changing state or richer behaviour.

Why is heavy use of static state considered a design smell?

Mutable static fields act as global variables: any code can change them, tests leak state into each other, and you cannot replace them with a fake. Static is fine for constants, pure helpers and factory methods, not for business state.