1.1 Classes, Objects & Memory Instantiation
← Back to Chapter 1: OOPs Concepts
At the heart of Java lies the distinction between a Class (a user-defined template or blueprint) and an Object (a concrete, runtime instance occupying memory).
1. Class vs Object: The Conceptual Difference
| Dimension | Class | Object (Instance) |
|---|---|---|
| Definition | Blueprint or template describing state & behavior | Runtime manifestation with identity, state, and behavior |
| Memory Allocation | Loaded once into JVM Metaspace (type metadata) | Allocated dynamically on the Heap at runtime |
| Lifecycle | Exists as long as its ClassLoader is active | Created via new, collected by Garbage Collector (GC) |
| Declaration | class Account { ... } | Account acc = new Account(); |
2. JVM Memory Allocation During Object Creation
When you execute:
Order order = new Order(101, "Laptop");
The JVM executes a precise multi-phase sequence:
- Class Verification & Loading: If
Order.classis not already loaded, theClassLoaderloads its bytecode into Metaspace. - Heap Memory Allocation: The JVM allocates contiguous bytes on the Java Heap to hold instance variables plus object header metadata (Mark Word + Klass Word = 12–16 bytes).
- Zero Initialization: Instance variables receive default values (
0,null,false). - Constructor Execution:
- Explicit field initializers execute.
- The constructor body runs to initialize custom state.
- Reference Assignment: The 32/64-bit reference address of the Heap object is pushed into the current thread's Stack Frame and assigned to local variable
order.
JVM Thread Stack JVM Heap Memory
┌─────────────────────────┐ ┌───────────────────────────────────┐
│ Frame: main() │ │ Object Header: Mark/Klass Words │
│ │ │ id: 101 │
│ [order] ───────────────┼────────────►│ description: "Laptop" (ref -> SCP)│
└─────────────────────────┘ └───────────────────────────────────┘
3. Anatomy of a Clean Java Class
package dev.codewithsarvy.oops;
public class Order {
// 1. Instance fields (encapsulated state)
private final long id;
private String item;
private double amount;
// 2. Constructors
public Order(long id, String item, double amount) {
if (amount < 0) {
throw new IllegalArgumentException("Amount cannot be negative");
}
this.id = id;
this.item = item;
this.amount = amount;
}
// 3. Business logic methods (behavior)
public void applyDiscount(double percentage) {
this.amount -= (this.amount * (percentage / 100.0));
}
// 4. Accessors
public long getId() { return id; }
public String getItem() { return item; }
public double getAmount() { return amount; }
}
Pro Tip: Java 14+ Records
For immutable data carriers, modern Java provides Records (record Order(long id, String item, double amount) {}), which automatically generate constructors, getters, equals(), hashCode(), and toString() at compile time.