Skip to main content

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​

DimensionClassObject (Instance)
DefinitionBlueprint or template describing state & behaviorRuntime manifestation with identity, state, and behavior
Memory AllocationLoaded once into JVM Metaspace (type metadata)Allocated dynamically on the Heap at runtime
LifecycleExists as long as its ClassLoader is activeCreated via new, collected by Garbage Collector (GC)
Declarationclass 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:

  1. Class Verification & Loading: If Order.class is not already loaded, the ClassLoader loads its bytecode into Metaspace.
  2. 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).
  3. Zero Initialization: Instance variables receive default values (0, null, false).
  4. Constructor Execution:
    • Explicit field initializers execute.
    • The constructor body runs to initialize custom state.
  5. 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.