java-tutorial

5) OOP Basics: Classes, Objects, Encapsulation

Goal

Understand how to model real concepts using classes, fields, constructors, and methods.

Class vs object

Example: a simple BankAccount

public class BankAccount {
    private final String id;
    private long balanceCents;

    public BankAccount(String id) {
        this.id = id;
        this.balanceCents = 0;
    }

    public void deposit(long cents) {
        if (cents <= 0) throw new IllegalArgumentException("cents must be positive");
        balanceCents += cents;
    }

    public void withdraw(long cents) {
        if (cents <= 0) throw new IllegalArgumentException("cents must be positive");
        if (cents > balanceCents) throw new IllegalStateException("insufficient funds");
        balanceCents -= cents;
    }

    public long getBalanceCents() {
        return balanceCents;
    }

    public String getId() {
        return id;
    }
}

Encapsulation

Exercises

  1. Add a transferTo(BankAccount other, long cents) method.
  2. Add validation to prevent null/blank id.
  3. Create a toString() that prints id and balance.

Table of contents

  1. Getting Started: Install, run, and your first program
  2. Java Basics: types, variables, operators, formatting
  3. Control Flow: if/switch/loops
  4. Methods: parameters, return values, overloading
  5. OOP: classes, objects, encapsulation
  6. Inheritance & Polymorphism (and when not to use them)
  7. Interfaces, abstract classes, and design basics
  8. Exceptions and error handling
  9. Strings, files, and I/O basics
  10. Collections: List/Set/Map and Big-O intuition
  11. Generics (the useful parts)
  12. Lambdas & Streams
  13. Dates and time (java.time)
  14. Testing with JUnit 5 (basics)
  15. Concurrency: threads, executors, futures
  16. JVM basics: memory, GC, performance habits
  17. Build tools: Maven essentials (recommended)
  18. Next steps: projects to build