04
Languages / Beginner → intermediate

Java and object-oriented programming

Java syntax, classes, interfaces, collections, exceptions, and clean object-oriented design.

javaoopclassesinterfacescollections

01OOP without overcomplication

Object-oriented programming is useful when a domain has entities with state and behavior. Encapsulation protects invariants; interfaces describe contracts; composition lets one object use another without forcing an inheritance hierarchy.

javaEncapsulating a stock invariant
public final class Product {
    private final String name;
    private int stock;

    public Product(String name, int stock) {
        if (name == null || name.isBlank()) {
            throw new IllegalArgumentException("name is required");
        }
        if (stock < 0) throw new IllegalArgumentException("stock < 0");
        this.name = name;
        this.stock = stock;
    }

    public void sell(int quantity) {
        if (quantity <= 0 || quantity > stock) {
            throw new IllegalArgumentException("invalid quantity");
        }
        stock -= quantity;
    }

    public int getStock() { return stock; }
}

02Collections

  • ArrayList: ordered dynamic sequence.
  • HashMap: key/value lookup.
  • HashSet: uniqueness and fast membership.
  • Deque: stack or queue behavior.
  • PriorityQueue: heap-backed priority processing.

03Design rules

  • Prefer small classes with clear responsibilities.
  • Program to interfaces at boundaries where multiple implementations make sense.
  • Do not create getters/setters for everything automatically; protect valid state.
  • Use checked/unchecked exceptions intentionally and never swallow errors silently.