Lesson · Classes and Objects
Classes and objects: references, not values
17 min readClasses, Objects & this
A class is a blueprint, an object is one instance of it, and your variable holds a reference rather than the object itself. That one sentence explains aliasing, null, identity and half of all OOP puzzles.
A class declares, new creates
A class declares structure: fields (the state each object carries) and methods (the behaviour that state supports). Nothing exists yet. new is what creates: it allocates an object on the heap, initialises its fields to defaults, runs a constructor, and hands back a reference to the result.
Three actors appear in every line of object-oriented code, and keeping them apart is half the battle:
| Term | What it is | Where it lives |
|---|---|---|
| Class | The blueprint: which fields, which methods | Loaded once per JVM, in metaspace |
| Object | One instance holding real values | The heap |
| Reference | A value that points at an object | In a variable: a stack frame, or inside another object |
One object can have many references; one reference points at exactly one object, or at null. Everything else in this lesson follows from that sentence.
What new does, in order
The expression new Person("Ada") looks atomic. It is four steps in a fixed order, and a surprising share of Java's rules come from that sequence.
- Allocate: heap space is reserved for one instance, sized from the class's fields, plus the object header the JVM adds to every object.
- Zero: every field is set to its default (0, false, null) in one sweep, before any constructor code runs.
- Initialise: the matching constructor runs, giving fields their first real values and validating them on the way.
- Return the reference: the whole expression evaluates to a reference to the new object, and that reference is what the variable receives.
There is no previous object to reuse. Construction always starts from defaults, which is why a constructor can trust a known floor and why stale state is impossible.
References, aliasing, and identity
Copy a reference and you have two remotes for one object. Person q = p; creates no new object; mutating through q is visible through p, because there was only ever one object. When that surprises someone, they were reading variables as boxes holding values, which is true for primitives and false for everything else.
The canonical worked example, four lines, traced in order:
| Question | Tool | Before anything is overridden |
|---|---|---|
| Same object? | == | Exact reference comparison, always |
| Same content? | equals | Falls back to == until the class overrides it |
| Usable as a map key? | hashCode plus equals | Identity hash until both are overridden together |
Person p = new Person("Ada");allocates object #1 and stores its reference in p.Person q = p;copies the reference. No object is created: p and q are two remotes for object #1.q.name = "Grace";writes through q into the shared object, so p reads Grace too. That is aliasing.Person r = new Person("Ada");allocates a separate object #2.p == ris false: different objects, even with equal content.
== asks about remotes; equals asks about content. The Object default answers the second question with the first, which is why every value-like class overrides equals and hashCode as a pair.
Stack and heap, step by step
Stack · locals
no variables yet
Heap · objects
nothing allocated yet
The code on the left runs against two kinds of memory: locals living on the stack as references, and objects living on the heap. Watch where each name points.
this: the current object
Inside an instance method, this is the remote control to the object the call was made on. The demo's System.out.println(p) prints Person[Grace] because println calls p.toString(), and that call runs with this == p. The mechanics are literal:
p.toString()compiles to an invocation with two inputs: the method to run, and the receiver (the object the call is sent to), herep.- Inside the body,
thisis that receiver. An unqualifiednameis reallythis.name. - A static method compiles without a receiver slot at all, which is exactly why it cannot read instance fields.
- Disambiguate:
this.name = name;when a parameter shadows a field. - Pass along: handing the current object to a collaborator inside the method.
- Return it:
return this;for fluent chains where calls stack on one object. - Chain constructors:
this(cents, "USD")as the first statement of another constructor, covered in the constructors topic.
this is an implicit parameter, not magic. Instance methods differ from static methods by one hidden argument, and that is the whole distinction.
State, identity, and what final really fixes
An object's identity never changes: the object created here is that object, however many references point at it, until no references remain and the garbage collector reclaims it. Identity and equality are different questions, and interviewers ask both.
final on an object variable fixes the reference, not the object, and the distinction multiplies across every place the keyword can appear:
| Declaration | Frozen | Still mutable |
|---|---|---|
final Person p; | Which object p points at | The object's fields |
final field | The field, once assigned | What the field points at, if that object is mutable |
| Immutable class | Everything, after construction | Nothing: changes produce new objects |
Identity is forever; equality is a choice. An object is itself until the garbage collector says otherwise; what equals means is whatever your class decides.
The reference playbook
Every object puzzle, in an interview or a failing test, reduces to the same four checks, in order:
- See an assignment? It copies the reference, not the object: count how many remotes now point at the same instance.
- See
==? Translate it to 'same object?'. Seeequals? Check whether the class actually defines content equality first. - See a mutation through one variable and a read through another? Trace both to the heap object before predicting anything.
- See a NullPointerException? Find the reference that points nowhere before blaming the method it called.
Variables are boxes for primitives and remotes for objects. == compares remotes, equals compares content, and null is a remote aimed at nothing.
final glues the remote, not the appliance
final on a reference type means the reference cannot be reassigned. The object behind it stays fully mutable unless the class is built to prevent it. Everyone meets this once with a final List: final stops list = otherList, while list.add(...) works all day.
Interview angles
What does a variable of object type actually hold?+
A reference: a value that points at an object on the heap. Assignment copies the reference, so two variables can name one object. This is also why Java's pass-by-value is subtle: methods receive a copy of the reference, so they can mutate the shared object but cannot repoint the caller's variable.
What is the difference between == and equals for objects?+
== is reference identity: same object or not. equals is content equality, defined by the class; the Object default falls back to ==, which is why classes that matter override it together with hashCode. For strings, Integer and other value-like types, equals is what you want.
What does final mean on an object reference?+
The reference cannot be reassigned after initialisation. The object is still mutable through that reference. Constraining the object itself requires an immutable class: final fields, no setters, defensive copies.
Where do objects and references live?+
Objects live on the heap; the reference (the local variable or a field) lives on the stack frame or inside the enclosing object. That split is why objects outlive the method that created them while locals do not.
Walk through what new does, in order.+
Allocates heap space for the instance, zeroes every field to its default in one sweep, runs the matching constructor, and evaluates to a reference. Constructors always start from the defaults, never from another object's leftovers.