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
| Kind | Declared inside | Needs outer instance? |
|---|---|---|
| Top-level | Own .java file | No |
| Static nested | Another class, marked static | No |
| Inner (non-static) | Another class, no static | Yes |
| Local | Inside a method | Yes (captures locals) |
| Anonymous | Inline 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
newallocates memory and initialises fields to defaults.- Parent constructor runs (explicit or implicit
super(...)). - Instance field initialisers and instance initialiser blocks run (top to bottom).
- The constructor body runs.
- The reference is returned to the caller.
- 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.