Skip to main content

Object-Oriented Programming in Java

Classes and objects​

public class Account {
private final String owner;
private double balance;

public Account(String owner, double balance) {
this.owner = owner;
this.balance = balance;
}

public void deposit(double amount) {
if (amount <= 0) throw new IllegalArgumentException("amount must be positive");
balance += amount;
}

public double getBalance() { return balance; }

@Override
public String toString() { return owner + ": " + balance; }
}

The four pillars​

PillarIdeaJava feature
EncapsulationHide state behind methodsprivate fields, getters and setters
InheritanceReuse and specialiseextends
PolymorphismOne interface, many behavioursOverriding, interfaces
AbstractionExpose what, hide howabstract classes, interfaces

Inheritance and polymorphism​

abstract class Shape {
abstract double area();
}

class Rectangle extends Shape {
private final double w, h;
Rectangle(double w, double h) { this.w = w; this.h = h; }
@Override double area() { return w * h; }
}

class Circle extends Shape {
private final double r;
Circle(double r) { this.r = r; }
@Override double area() { return Math.PI * r * r; }
}

Shape[] shapes = { new Rectangle(2, 3), new Circle(1) };
for (Shape s : shapes) System.out.println(s.area()); // dynamic dispatch

Interfaces​

interface Payable {
double amountDue();
default String label() { return "Payable"; } // default method
}

A class can implement many interfaces but extend only one class.

Useful concepts​

ConceptNotes
Overloading vs overridingSame name, different parameters / same signature in a subclass
staticBelongs to the class, not an instance
finalCannot be reassigned, overridden or extended
Access modifiersprivate, package-private, protected, public
equals and hashCodeOverride together for use in hash-based collections
Records (Java 16+)record Point(int x, int y) {} for immutable data classes