Back to JDK, JRE & JVM
Q5Question 5 of 5

What are classes, objects, constructors, and object lifecycle in Java

Answer: A class is a blueprint defining state (fields) and behavior (methods), an object is a heap-allocated instance created by the new keyword and a constructor, and the JVM manages the object lifecycle from allocation through garbage collection.

Key Concepts
  • A class is a blueprint that defines fields, methods, and constructors; an object is a runtime instance of that class allocated on the heap.
  • A constructor is a special method called when an object is created with new; it initializes the object's fields and has no return type.
  • Java provides a default no-arg constructor only if you do not define any constructor yourself.
  • Constructor chaining uses this() to call another constructor in the same class and super() to call the parent class constructor.
  • The object lifecycle is: class loading, memory allocation on the heap, constructor execution, usage, becoming unreachable, and garbage collection.
  • Static factory methods (e.g., Account.of()) are an alternative to public constructors, giving you naming, caching, and subtype control.
  • Java records (Java 16+) auto-generate a canonical constructor, getters, equals, hashCode, and toString from the component list.

Definition

A class is a blueprint defining state (fields) and behavior (methods), an object is a heap-allocated instance created by the new keyword and a constructor, and the JVM manages the object lifecycle from allocation through garbage collection.
  • Class is a template that defines the fields (state), methods (behavior), and constructors for creating objects.
  • Object is a runtime instance of a class, allocated on the JVM heap, with its own copy of instance fields.
  • Constructor is a special method with no return type, called when new is used, that initializes the object's fields.
  • Default constructor is the no-arg constructor Java generates automatically if and only if you do not define any constructor.
  • Object lifecycle is the sequence from class loading to heap allocation, constructor execution, field initialization, usage, becoming unreachable, and garbage collection.

Think of National Bank of India opening new accounts. The Account class is the paper form template that defines the fields: account ID, holder name, balance. When Rajesh fills out the form for Priya, he creates an object (a specific account with SAV2001, Priya, 100000 INR). The constructor is the step where the clerk stamps the form and assigns the values. When Priya closes the account and all references to it are gone, the bank archives it (garbage collection). If another customer needs the same template, they get a fresh copy of the form (new object), not Priya's old one.

Understanding the Concepts

What is a class in Java?

A class is a blueprint that defines the state (fields) and behavior (methods) of objects. It also defines constructors, which are special methods for creating and initializing objects. A class can have static members (shared across all instances) and instance members (unique to each object).

JAVA
package com.bank.core;

import java.math.BigDecimal;

public class AccountClass {

    // Fields (state)
    private String accountId;
    private String holderName;
    private BigDecimal balance;

    // Constructor (initialization)
    public AccountClass(String accountId, String holderName, BigDecimal balance) {
        this.accountId = accountId;
        this.holderName = holderName;
        this.balance = balance;
    }

    // Method (behavior)
    public void printDetails() {
        System.out.println(accountId + " | " + holderName + " | " + balance + " INR");
    }

    public static void main(String[] args) {
        var account = new AccountClass("SAV2001", "Rajesh", new BigDecimal("150000.00"));
        System.out.println("Class: " + account.getClass().getName());
        System.out.println("Object: ");
        account.printDetails();
    }
}
TEXT
Expected output:
Class: com.bank.core.AccountClass
Object: 
SAV2001 | Rajesh | 150000.00 INR

What is an object and how is it created?

An object is a runtime instance of a class. It is created using the new keyword, which allocates memory on the JVM heap and calls the constructor to initialize the fields. Each object has its own copy of instance fields.

  • The new keyword does three things:
  • Allocates memory on the heap for the object.
  • Calls the constructor to initialize fields.
  • Returns a reference (pointer) to the object.
JAVA
package com.bank.core;

import java.math.BigDecimal;

public class ObjectCreationDemo {

    static class Account {
        String accountId;
        BigDecimal balance;

        Account(String accountId, BigDecimal balance) {
            System.out.println("  Constructor called for " + accountId);
            this.accountId = accountId;
            this.balance = balance;
        }
    }

    public static void main(String[] args) {
        System.out.println("Creating objects:");
        var acc1 = new Account("SAV2001", new BigDecimal("150000.00"));
        var acc2 = new Account("CUR3001", new BigDecimal("500000.00"));

        System.out.println("\nacc1 and acc2 are different objects:");
        System.out.println("  acc1 == acc2: " + (acc1 == acc2));
        System.out.println("  acc1.accountId: " + acc1.accountId);
        System.out.println("  acc2.accountId: " + acc2.accountId);

        // References: acc3 points to the same object as acc1
        var acc3 = acc1;
        System.out.println("\nacc3 = acc1 (same reference):");
        System.out.println("  acc1 == acc3: " + (acc1 == acc3));
    }
}
TEXT
Expected output:
Creating objects:
  Constructor called for SAV2001
  Constructor called for CUR3001

acc1 and acc2 are different objects:
  acc1 == acc2: false
  acc1.accountId: SAV2001
  acc2.accountId: CUR3001

acc3 = acc1 (same reference):
  acc1 == acc3: true

What are constructors and what types exist?

A constructor is a special method that initializes an object. It has the same name as the class and no return type. Java supports several types of constructors:

  1. Default constructor: generated by Java if you write none. It takes no arguments and does nothing.
  2. Parameterized constructor: takes arguments to initialize fields.
  3. Copy constructor: takes another object of the same class and copies its fields.
  4. Constructor chaining: using this() to call another constructor in the same class.
JAVA
package com.bank.core;

import java.math.BigDecimal;

public class ConstructorTypes {

    static class Account {
        String accountId;
        String holderName;
        BigDecimal balance;

        // Parameterized constructor
        Account(String accountId, String holderName, BigDecimal balance) {
            this.accountId = accountId;
            this.holderName = holderName;
            this.balance = balance;
        }

        // Constructor chaining: default balance
        Account(String accountId, String holderName) {
            this(accountId, holderName, BigDecimal.ZERO); // calls the 3-arg constructor
        }

        // Copy constructor
        Account(Account other) {
            this(other.accountId + "-COPY", other.holderName, other.balance);
        }

        @Override
        public String toString() {
            return accountId + " | " + holderName + " | " + balance + " INR";
        }
    }

    public static void main(String[] args) {
        var acc1 = new Account("SAV2001", "Rajesh", new BigDecimal("150000.00"));
        var acc2 = new Account("CUR3001", "Priya"); // uses chained constructor
        var acc3 = new Account(acc1); // copy constructor

        System.out.println("Parameterized: " + acc1);
        System.out.println("Chained (zero balance): " + acc2);
        System.out.println("Copy: " + acc3);
    }
}
TEXT
Expected output:
Parameterized: SAV2001 | Rajesh | 150000.00 INR
Chained (zero balance): CUR3001 | Priya | 0 INR
Copy: SAV2001-COPY | Rajesh | 150000.00 INR

How is a constructor different from a static factory method?

A static factory method is a static method that returns an instance of the class. It provides advantages over public constructors: you can name the method, return a cached instance, return a subtype, or perform validation before creating the object.

FeatureConstructorStatic Factory Method
Invocationnew Account(...)Account.of(...)
NamingAlways the class nameAny descriptive name
Return typeAlways the classCan return a subtype
CachingAlways creates new objectCan return cached instance
ValidationCan throw in constructorCan return Optional or null
InheritanceSubclass calls super()Can return different subclass
DiscoverabilityWell-known conventionMust know the method name
JAVA
package com.bank.core;

import java.math.BigDecimal;

public class StaticFactoryDemo {

    static class Account {
        private final String accountId;
        private final String type;
        private final BigDecimal balance;

        private Account(String accountId, String type, BigDecimal balance) {
            this.accountId = accountId;
            this.type = type;
            this.balance = balance;
        }

        // Static factory methods with descriptive names
        public static Account savings(String id, BigDecimal balance) {
            return new Account(id, "SAVINGS", balance);
        }

        public static Account current(String id, BigDecimal balance) {
            return new Account(id, "CURRENT", balance);
        }

        public static Account zeroBalance(String id) {
            return new Account(id, "SAVINGS", BigDecimal.ZERO);
        }

        @Override
        public String toString() {
            return accountId + " [" + type + "] " + balance + " INR";
        }
    }

    public static void main(String[] args) {
        var sav = Account.savings("SAV2001", new BigDecimal("150000.00"));
        var cur = Account.current("CUR3001", new BigDecimal("500000.00"));
        var zero = Account.zeroBalance("SAV2002");

        System.out.println("Static factory methods:");
        System.out.println("  " + sav);
        System.out.println("  " + cur);
        System.out.println("  " + zero);
    }
}
TEXT
Expected output:
Static factory methods:
  SAV2001 [SAVINGS] 150000.00 INR
  CUR3001 [CURRENT] 500000.00 INR
  SAV2002 [SAVINGS] 0 INR

What is the object lifecycle in the JVM?

The lifecycle of a Java object has these phases:

  1. Class loading: the JVM loads the .class file into the method area.
  2. Memory allocation: new allocates space on the heap (young generation).
  3. Constructor execution: fields are initialized, constructor body runs.
  4. In use: the object is referenced and used by the application.
  5. Unreachable: no live reference points to the object.
  6. Garbage collection: the GC reclaims the heap memory.

The finalize() method is deprecated since Java 9. Use java.lang.ref.Cleaner for cleanup actions.

JAVA
package com.bank.core;

import java.lang.ref.Cleaner;
import java.math.BigDecimal;

public class ObjectLifecycleDemo {

    private static final Cleaner cleaner = Cleaner.create();

    static class Account implements AutoCloseable {
        String accountId;
        BigDecimal balance;
        Cleaner.Cleanable cleanable;

        Account(String accountId, BigDecimal balance) {
            this.accountId = accountId;
            this.balance = balance;
            // Register cleanup action with Cleaner
            this.cleanable = cleaner.register(this, () ->
                System.out.println("  Cleaner: releasing resources for " + accountId));
            System.out.println("  Created: " + accountId + " (" + balance + " INR)");
        }

        @Override
        public void close() {
            cleanable.clean();
        }
    }

    public static void main(String[] args) {
        System.out.println("Object lifecycle demo:");

        System.out.println("\n1. Construction:");
        try (var acc = new Account("SAV2001", new BigDecimal("150000.00"))) {
            System.out.println("\n2. In use:");
            System.out.println("  Balance: " + acc.balance + " INR");
            System.out.println("\n3. Close (try-with-resources):");
        }

        System.out.println("\n4. Unreachable: object has no references");
        System.out.println("5. GC will reclaim memory (not deterministic)");
    }
}
TEXT
Expected output:
Object lifecycle demo:

1. Construction:
  Created: SAV2001 (150000.00 INR)

2. In use:
  Balance: 150000.00 INR

3. Close (try-with-resources):
  Cleaner: releasing resources for SAV2001

4. Unreachable: object has no references
5. GC will reclaim memory (not deterministic)

What is a complete banking project showing classes, constructors, and lifecycle?

This project defines Account with multiple constructors, a static factory, and demonstrates the object lifecycle with Cleaner.

Project structure

DIAGRAM
bank-account-lifecycle/
├── src/
│   └── main/
│       └── java/
│           └── com/
│               └── bank/
│                   └── core/
│                       ├── BankAccount.java
│                       ├── AccountFactory.java
│                       └── AccountLifecycleApp.java
└── run.sh

BankAccount.java

JAVA
package com.bank.core;

import java.math.BigDecimal;

public class BankAccount {
    private final String accountId;
    private final String holderName;
    private final String type;
    private BigDecimal balance;

    // Full constructor
    public BankAccount(String accountId, String holderName, String type, BigDecimal balance) {
        this.accountId = accountId;
        this.holderName = holderName;
        this.type = type;
        this.balance = balance;
    }

    // Chained: default type SAVINGS
    public BankAccount(String accountId, String holderName, BigDecimal balance) {
        this(accountId, holderName, "SAVINGS", balance);
    }

    // Chained: zero balance
    public BankAccount(String accountId, String holderName) {
        this(accountId, holderName, BigDecimal.ZERO);
    }

    // Copy constructor
    public BankAccount(BankAccount other) {
        this(other.accountId + "-COPY", other.holderName, other.type, other.balance);
    }

    public void deposit(BigDecimal amount) {
        balance = balance.add(amount);
    }

    public String getAccountId() { return accountId; }
    public BigDecimal getBalance() { return balance; }

    @Override
    public String toString() {
        return accountId + " [" + type + "] " + holderName + ": " + balance + " INR";
    }
}

AccountFactory.java

JAVA
package com.bank.core;

import java.math.BigDecimal;

public class AccountFactory {

    public static BankAccount savingsAccount(String id, String name, BigDecimal balance) {
        return new BankAccount(id, name, "SAVINGS", balance);
    }

    public static BankAccount currentAccount(String id, String name, BigDecimal balance) {
        return new BankAccount(id, name, "CURRENT", balance);
    }

    public static BankAccount zeroBalanceAccount(String id, String name) {
        return new BankAccount(id, name);
    }
}

AccountLifecycleApp.java

JAVA
package com.bank.core;

import java.math.BigDecimal;

public class AccountLifecycleApp {
    public static void main(String[] args) {
        System.out.println("=== National Bank of India: Account Lifecycle ===");

        // Constructor types
        System.out.println("\n--- Constructor Types ---");
        var acc1 = new BankAccount("SAV2001", "Rajesh", "SAVINGS", new BigDecimal("150000.00"));
        var acc2 = new BankAccount("CUR3001", "Priya", new BigDecimal("500000.00"));
        var acc3 = new BankAccount("SAV2002", "Pankaj");
        var acc4 = new BankAccount(acc1);

        System.out.println("Full:    " + acc1);
        System.out.println("Chained: " + acc2);
        System.out.println("Zero:    " + acc3);
        System.out.println("Copy:    " + acc4);

        // Static factory
        System.out.println("\n--- Static Factory ---");
        var sav = AccountFactory.savingsAccount("SAV3001", "Rajesh", new BigDecimal("200000.00"));
        var cur = AccountFactory.currentAccount("CUR4001", "Priya", new BigDecimal("750000.00"));
        System.out.println("Factory savings: " + sav);
        System.out.println("Factory current: " + cur);

        // Object independence
        System.out.println("\n--- Object Independence ---");
        acc1.deposit(new BigDecimal("50000.00"));
        System.out.println("acc1 after deposit: " + acc1.getBalance() + " INR");
        System.out.println("acc4 (copy) unchanged: " + acc4.getBalance() + " INR");
    }
}

How to compile and run

BASH
javac -d out src/main/java/com/bank/core/*.java
java -cp out com.bank.core.AccountLifecycleApp
TEXT
Expected output:
=== National Bank of India: Account Lifecycle ===

--- Constructor Types ---
Full:    SAV2001 [SAVINGS] Rajesh: 150000.00 INR
Chained: CUR3001 [SAVINGS] Priya: 500000.00 INR
Zero:    SAV2002 [SAVINGS] Pankaj: 0 INR
Copy:    SAV2001-COPY [SAVINGS] Rajesh: 150000.00 INR

--- Static Factory ---
Factory savings: SAV3001 [SAVINGS] Rajesh: 200000.00 INR
Factory current: CUR4001 [CURRENT] Priya: 750000.00 INR

--- Object Independence ---
acc1 after deposit: 200000.00 INR
acc4 (copy) unchanged: 150000.00 INR

What are common mistakes with constructors?

The most common mistake is relying on the default constructor after adding a parameterized one. Java only generates a default no-arg constructor if you define no constructors at all.

Wrong: expecting default constructor after adding a parameterized one

JAVA
package com.bank.core;

import java.math.BigDecimal;

public class WrongDefaultConstructor {

    static class Account {
        String accountId;
        BigDecimal balance;

        // Parameterized constructor exists
        Account(String accountId, BigDecimal balance) {
            this.accountId = accountId;
            this.balance = balance;
        }
    }

    public static void main(String[] args) {
        // This compiles fine
        var acc1 = new Account("SAV2001", new BigDecimal("100000"));
        System.out.println("Parameterized: " + acc1.accountId);

        // This would NOT compile:
        // var acc2 = new Account(); // error: no default constructor
        System.out.println("new Account() would fail: no default constructor");
        System.out.println("Java only generates a default constructor if you define NONE");
    }
}
TEXT
Expected output:
Parameterized: SAV2001
new Account() would fail: no default constructor
Java only generates a default constructor if you define NONE

Correct: explicitly define both constructors

JAVA
package com.bank.core;

import java.math.BigDecimal;

public class CorrectExplicitConstructors {

    static class Account {
        String accountId;
        BigDecimal balance;

        Account() {
            this("UNKNOWN", BigDecimal.ZERO);
        }

        Account(String accountId, BigDecimal balance) {
            this.accountId = accountId;
            this.balance = balance;
        }
    }

    public static void main(String[] args) {
        var acc1 = new Account();
        var acc2 = new Account("SAV2001", new BigDecimal("100000"));

        System.out.println("No-arg: " + acc1.accountId + " " + acc1.balance + " INR");
        System.out.println("With args: " + acc2.accountId + " " + acc2.balance + " INR");
    }
}
TEXT
Expected output:
No-arg: UNKNOWN 0 INR
With args: SAV2001 100000 INR

What about Java records?

Java records (Java 16+) are a concise way to define immutable data classes. The compiler generates the canonical constructor, getters (component accessors), equals, hashCode, and toString from the component list. You can also define a compact constructor for validation.

JAVA
package com.bank.core;

import java.math.BigDecimal;

public class RecordDemo {

    // Record auto-generates constructor, getters, equals, hashCode, toString
    record Account(String accountId, String holderName, BigDecimal balance) {

        // Compact constructor for validation
        Account {
            if (balance.compareTo(BigDecimal.ZERO) < 0) {
                throw new IllegalArgumentException("Balance cannot be negative: " + balance);
            }
        }
    }

    public static void main(String[] args) {
        var acc1 = new Account("SAV2001", "Rajesh", new BigDecimal("150000.00"));
        var acc2 = new Account("SAV2001", "Rajesh", new BigDecimal("150000.00"));

        System.out.println("Record: " + acc1);
        System.out.println("Getter: " + acc1.accountId());
        System.out.println("equals: " + acc1.equals(acc2));
        System.out.println("hashCode match: " + (acc1.hashCode() == acc2.hashCode()));

        try {
            new Account("SAV2002", "Priya", new BigDecimal("-1000.00"));
        } catch (IllegalArgumentException e) {
            System.out.println("Validation: " + e.getMessage());
        }
    }
}
TEXT
Expected output:
Record: Account[accountId=SAV2001, holderName=Rajesh, balance=150000.00]
Getter: SAV2001
equals: true
hashCode match: true
Validation: Balance cannot be negative: -1000.00

What should a senior or principal engineer know?

At the senior level, you should understand the implications of object creation on performance and memory, and when to use records vs classes.

At the principal level, consider:

  • Escape analysis: the JVM can allocate short-lived objects on the stack instead of the heap if the object does not escape the method.
  • Object pooling: for expensive-to-create objects (database connections, thread pools), reuse instances instead of creating new ones.
  • TLAB (Thread-Local Allocation Buffer): each thread has a private allocation area in the young generation, making new() lock-free.
  • Compact constructors in records: validate invariants in the compact constructor, which runs before field assignment.
  • Sealed classes: restrict which classes can extend a type, enabling exhaustive pattern matching in switch expressions.
  • Initialization order: static fields, static block, instance fields, instance block, constructor body, in that order.
JAVA
package com.bank.core;

public class SeniorObjectKnowledge {

    static class Account {
        static { System.out.println("  1. Static block"); }
        { System.out.println("  3. Instance block"); }

        String accountId;

        Account(String accountId) {
            System.out.println("  4. Constructor body");
            this.accountId = accountId;
        }
    }

    public static void main(String[] args) {
        System.out.println("Senior/Principal object checklist:");
        System.out.println("  1. Escape analysis: JVM may stack-allocate short-lived objects");
        System.out.println("  2. TLAB: new() is lock-free per thread");
        System.out.println("  3. Object pools for expensive resources (DB connections)");
        System.out.println("  4. Records for immutable data, classes for mutable state");
        System.out.println("  5. Sealed classes for exhaustive pattern matching");

        System.out.println("\nInitialization order:");
        System.out.println("  2. Instance field defaults");
        new Account("SAV2001");
    }
}
TEXT
Expected output:
Senior/Principal object checklist:
  1. Escape analysis: JVM may stack-allocate short-lived objects
  2. TLAB: new() is lock-free per thread
  3. Object pools for expensive resources (DB connections)
  4. Records for immutable data, classes for mutable state
  5. Sealed classes for exhaustive pattern matching

Initialization order:
  2. Instance field defaults
  1. Static block
  3. Instance block
  4. Constructor body

What are common interview follow-up questions?

  • Can a constructor be private? (Yes. It is used in Singleton pattern, static factory methods, and utility classes with only static methods.)
  • What is the difference between this() and super()? (this() calls another constructor in the same class. super() calls the parent class constructor. Both must be the first statement in the constructor.)
  • Can you call a constructor without new? (Not directly. Reflection (Constructor.newInstance()), deserialization, and cloning bypass new, but they still invoke or skip constructors in specific ways.)
  • What happens if a constructor throws an exception? (The object is partially constructed. If new threw, the reference is never assigned, and the partially constructed object becomes eligible for GC.)
  • What is the difference between a class and a record? (A record is implicitly final, has all fields final, and auto-generates constructor, getters, equals, hashCode, toString. A class gives full control over mutability and inheritance.)
  • When should you use a builder pattern instead of a constructor? (When the class has many optional parameters. A builder provides readable, fluent construction: Account.builder().accountId("SAV2001").balance(100000).build().)

Visual Overview

DIAGRAM
 Object Lifecycle in the JVM
 =============================

  1. Class Loading
  ┌──────────────────────────┐
  │ ClassLoader loads         │
  │ Account.class into        │
  │ Method Area               │
  └───────────┬──────────────┘
              │
              ▼
  2. Memory Allocation
  ┌──────────────────────────┐
  │ new Account(...)          │
  │ JVM allocates on heap     │
  │ (Young Generation / TLAB) │
  └───────────┬──────────────┘
              │
              ▼
  3. Constructor Execution
  ┌──────────────────────────┐
  │ super() (Object)          │
  │ Instance initializers     │
  │ Constructor body          │
  │ Fields assigned           │
  └───────────┬──────────────┘
              │
              ▼
  4. In Use
  ┌──────────────────────────┐
  │ Application holds         │
  │ reference to object       │
  │ acc.deposit(50000)        │
  └───────────┬──────────────┘
              │
              ▼
  5. Unreachable
  ┌──────────────────────────┐
  │ acc = null                │
  │ No live reference         │
  │ Object eligible for GC    │
  └───────────┬──────────────┘
              │
              ▼
  6. Garbage Collection
  ┌──────────────────────────┐
  │ GC reclaims heap memory   │
  │ Cleaner runs if registered│
  │ Memory returned to pool   │
  └──────────────────────────┘
DIAGRAM
 Constructor Chaining
 =====================

  new BankAccount("SAV2001", "Rajesh")
       │
       │ this(id, name, BigDecimal.ZERO)
       ▼
  BankAccount(String, String, BigDecimal)
       │
       │ this(id, name, "SAVINGS", balance)
       ▼
  BankAccount(String, String, String, BigDecimal)
       │
       │ super()  [implicit call to Object()]
       ▼
  Object()
       │
       ▼
  Fields initialized, constructor body runs

Key Takeaway

A class is a blueprint that defines fields, methods, and constructors. An object is a runtime instance of that class, created with the new keyword, which allocates heap memory and calls the constructor. Each object has its own copy of instance fields, so modifying one object does not affect another.

Constructors initialize objects. Java provides a default no-arg constructor only if you define none. Constructor chaining with this() lets you avoid duplicating initialization logic across multiple constructors. Copy constructors create independent copies of objects. Static factory methods offer naming, caching, and subtype flexibility that constructors cannot provide.

The object lifecycle in the JVM goes from class loading to heap allocation, constructor execution, usage, becoming unreachable, and garbage collection. The deprecated finalize() method is replaced by java.lang.ref.Cleaner for deterministic cleanup. In production, use try-with-resources for objects that hold external resources.

Java records (Java 16+) are the modern way to define immutable data carriers. They auto-generate the canonical constructor, getters, equals, hashCode, and toString. Use a compact constructor to validate invariants. Records are ideal for DTOs, value objects, and event payloads in banking systems.

At the senior level, understand escape analysis (JVM may stack-allocate short-lived objects), TLAB (thread-local allocation makes new() lock-free), and initialization order (static block, instance block, constructor body). For classes with many optional parameters, use the Builder pattern.

Remember one sentence: a class is the blueprint, an object is the heap-allocated instance created by the constructor, and in modern Java, prefer records for immutable data and static factory methods for flexible construction.

---

Share
Use ← → arrow keys to navigate