Chapter 04Part II · Objects
Classes, Objects and References
In this chapter: what an object physically is, where it lives, what a reference variable really holds, and how "a class that just holds data" went from forty lines of boilerplate in Java 7 to one line in Java 16.
Key points
- A class is a blueprint; an object is an instance created at run time with
new, always on the heap. - A reference variable holds a reference to an object, not the object. Copying a reference shares the object.
- Printing an object shows
ClassName@plus its hash code in hex. That's not a memory address. ==compares references;equals()compares meaning, but only if the class overrides it.- A data class needed hand-written
equals,hashCodeandtoStringin Java 7. A record (Java 16) generates them:record Money(String currency, long cents) {}.
Classes, objects and the three pillars
Object-oriented programming models a program as objects that combine state (fields) and behavior (methods). The core ideas are often summed up with the acronym PIE:
- Polymorphism: one interface, many implementations (Chapter 6).
- Inheritance: a class built on another class (Chapter 7).
- Encapsulation: hiding state behind methods, enforced by access modifiers (Chapter 9).
Abstraction, the fourth idea often listed with these, gets Chapter 8.
A class is a compile-time description. Nothing exists in memory for it until the JVM loads it, and no object exists until you ask for one.
The classic rule
"Rule → In Java objects are made dynamically only. The new operator allocates memory only to the object."
Still true: every object comes from new (or from something that calls it for you, such as reflection or deserialization), and its memory is allocated at run time.
Where things live
flowchart LR
subgraph META["Method area (Metaspace)"]
CLS["class Point<br/>method bytecode<br/>static fields"]
end
subgraph STACK["Stack of main()"]
P["p = ●"]
Q["q = ●"]
end
subgraph HEAP["Heap"]
OBJ["Point object<br/>x = 10<br/>y = 0"]
end
P --> OBJ
Q --> OBJ
OBJ -. "knows its class" .-> CLS
- The class (its methods' code and its
staticfields) exists once, in the method area. - Each object lives on the heap and holds its own copy of every instance field, plus a small header that, among other things, points to its class.
- Methods are not copied per object. Every
Pointshares the same method code; when a method runs, it receives the object it's working on as a hiddenthisparameter.
References: two names, one object
public class References {
public static void main(String[] args) {
Point p = new Point(); // one object on the heap
Point q = p; // a second reference to the SAME object
q.x = 10;
System.out.println("p.x = " + p.x); // 10: one object, two names
q = new Point(); // q now refers to a new object; p is unaffected
q.x = 99;
System.out.println("p.x = " + p.x + ", q.x = " + q.x);
System.out.println("p == q ? " + (p == q));
}
}
Point q = p copies the reference, not the object. Both variables now lead to the same object, so a change made through q is visible through p. Assigning q = new Point() points q somewhere else and leaves p alone.
The classic rule
"Rule → The Reference ID of one object can be put into any number of Reference Variables."
What does println(object) show?
public class PrintReference {
public static void main(String[] args) {
Point p = new Point();
String text = p.toString(); // what println(p) prints
String expected = "Point@" + Integer.toHexString(p.hashCode());
System.out.println("looks like Point@<hex>: "
+ text.startsWith("Point@"));
System.out.println("hex is the hash code: "
+ text.equals(expected));
}
}
Object.toString() returns the class name, @, and the object's hashCode() in hexadecimal.
A common misconception
Java 7-era tutorials often called this a "reference ID" or address. It isn't. The JVM moves objects around during garbage collection, so a fixed address couldn't be printed meaningfully, and the default hash code is a number the JVM generates once and stores in the object header. Java deliberately gives you no way to see an object's address.
Equality: == vs. equals()
== on references asks "are these the same object?" equals() asks "do these mean the same thing?" But Object.equals is just ==, so a class must override equals (and hashCode, which must agree with it) to get value equality.
The Java 7 way
import java.util.Objects;
public class Money7 { // the Java 7 way: write it all by hand
private final String currency;
private final long cents;
public Money7(String currency, long cents) {
this.currency = Objects.requireNonNull(currency); // Objects: Java 7
this.cents = cents;
}
public String currency() { return currency; }
public long cents() { return cents; }
@Override public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Money7)) return false;
Money7 m = (Money7) o;
return cents == m.cents && currency.equals(m.currency);
}
@Override public int hashCode() { return Objects.hash(currency, cents); }
@Override public String toString() {
return "Money7[currency=" + currency + ", cents=" + cents + "]";
}
public static void main(String[] args) {
Money7 a = new Money7("USD", 1250);
Money7 b = new Money7("USD", 1250);
System.out.println(a + " ==: " + (a == b)
+ " equals: " + a.equals(b));
}
}
Java 7 added java.util.Objects, whose requireNonNull, equals and hash made this boilerplate safer. It was still about thirty lines for two fields, and every new field meant updating three methods by hand. Forgetting one was a classic bug: two "equal" objects that land in different HashMap buckets.
The modern way: records (Java 16)
public class MoneyRecord {
record Money(String currency, long cents) { } // Java 16: one line
public static void main(String[] args) {
Money a = new Money("USD", 1250);
Money b = new Money("USD", 1250);
System.out.println(a + " ==: " + (a == b)
+ " equals: " + a.equals(b));
System.out.println("same hashCode: "
+ (a.hashCode() == b.hashCode()));
System.out.println("accessor: " + a.cents());
}
}
A record (JEP 395) declares its fields in its header and gets, for free:
- private
finalfields and a constructor that sets them, - accessor methods named after the fields (
cents(), notgetCents()), equals,hashCodeandtoStringbased on all fields.
Records are deliberately limited: they're immutable, can't extend another class, and can't add instance fields beyond the header. That's the point: a record says "this is just data." Chapter 19 shows what records do together with sealed types and pattern matching.
Migration tip
Look for classes that only hold data and have hand-written equals/hashCode, or that use Lombok's @Value. They're usually drop-in record candidates. Watch for two differences: accessors lose the get prefix, and records are always immutable.
Go deeper in the complete edition
This page is the focused edition. The complete edition of this chapter on GitHub adds the deep dives, puzzles, exercises and interview questions, with every sample ready to run.
Summary
- Objects are created with
newon the heap; classes and their code live once in the method area. - Reference variables hold references. Copying a reference shares the object.
- The default
toStringshows the hash code, not an address. ==checks identity; overrideequalsandhashCodefor value equality, or use a record (Java 16).
Next: Chapter 5 covers how objects get built: constructors, initializer blocks, static, and the Java 25 change to what you can write before super().