Classes and Objects in Java

A class is a blueprint. An object (instance) is what new ClassName(...) returns. A Java program is a collection of classes that collaborate by creating objects and calling their methods.

Anatomy of a class

public class BankAccount {

    // --- Fields (state) ---
    private final String owner;
    private BigDecimal balance;

    // --- Constructors ---
    public BankAccount(String owner, BigDecimal initialBalance) {
        this.owner   = Objects.requireNonNull(owner, "owner");
        this.balance = Objects.requireNonNull(initialBalance, "balance");
    }

    public BankAccount(String owner) {                    // overloaded
        this(owner, BigDecimal.ZERO);                     // delegates
    }

    // --- Methods (behaviour) ---
    public void deposit(BigDecimal amount) {
        if (amount.signum() <= 0) throw new IllegalArgumentException("> 0");
        balance = balance.add(amount);
    }

    public BigDecimal balance() { return balance; }
}

Creating objects

var a = new BankAccount("Alice", new BigDecimal("100.00"));
a.deposit(new BigDecimal("50.00"));

Top-level vs nested classes

KindDeclared insideNeeds outer instance?
Top-levelOwn .java fileNo
Static nestedAnother class, marked staticNo
Inner (non-static)Another class, no staticYes
LocalInside a methodYes (captures locals)
AnonymousInline with new Type() { ... }Yes

When to use a record or enum instead

  • Record β€” the class is a pure data carrier and should be immutable.
  • Enum β€” the class has a fixed, finite number of instances (Color.RED, Day.MONDAY).
  • Regular class β€” everything else, especially classes with evolving mutable state.

this β€” what it refers to

public class Counter {
    private int count;
    public Counter(int count) {
        this.count = count;       // disambiguate field from parameter
    }
    public Counter increment() {
        this.count++;
        return this;              // fluent chaining
    }
}

Object lifecycle

  1. new allocates memory and initialises fields to defaults.
  2. Parent constructor runs (explicit or implicit super(...)).
  3. Instance field initialisers and instance initialiser blocks run (top to bottom).
  4. The constructor body runs.
  5. The reference is returned to the caller.
  6. When no reference to the object remains, the garbage collector reclaims the memory.

Common mistakes

  • Public fields β€” see encapsulation.
  • God class β€” 1000+ line classes with dozens of responsibilities. Split them.
  • Misusing this β€” only needed to disambiguate or enable fluent chaining. Don't prefix every field access.
  • Static inner classes declared non-static β€” captures a silent reference to the outer instance, a common memory leak.

Related

Pillar: OOP. Siblings: constructors, records, encapsulation.