CodeNFacts
CodeHub
Home

All Categories


Sign In
CodeNFacts / OOP

Object-Oriented Programming with Java

Every concept, every pillar, every diagram you need - what OOP is, why it exists, how Java implements it, and how it's actually used in real systems. Read it here, or grab the full notes below.

Markdown notes · instant download
01 · Foundations

What is OOP, and why does it exist?

What is it?

A paradigm that organizes code around objects — self-contained units combining data (fields) and behavior (methods) — instead of a linear list of instructions.

Why use it?

It mirrors how we naturally think about the real world — cars, accounts, employees — so code maps to problem domains instead of fighting them. It also keeps large codebases maintainable.

Why is it needed?

Procedural code with shared global state gets fragile fast. OOP contains change: fixing or extending one class shouldn't force you to touch ten unrelated functions.

Object-Oriented ProgrammingEncapsulationInheritancePolymorphismAbstraction
02 · Comparison

Procedural vs Object-Oriented

ApproachProcedural (C-style)Object-Oriented (Java)
Unit of designFunctions acting on dataObjects bundling data + behavior
Data safetyGlobal/shared data, easily corruptedEncapsulated, access-controlled
Code reuseCopy-paste or function librariesInheritance & composition
ScalabilityGets tangled as codebase growsModular — classes evolve independently
Real-world mappingLow — thinks in stepsHigh — thinks in entities & relationships
Change impactRipples across functionsContained inside the responsible class
03 · Building block

Classes & Objects

A class is the blueprint. An object is the thing you actually build from it.

Car- brand: String- speed: int- fuel: double+ accelerate()+ brake()+ refuel()class = blueprint · object = built instance
Car.java
public class Car {
    private String brand;
    private int speed;

    // constructor
    public Car(String brand) {
        this.brand = brand;
        this.speed = 0;
    }

    public void accelerate(int amount) {
        speed += amount;
    }

    public void printStatus() {
        System.out.println(brand + " is going " + speed + " km/h");
    }
}

// creating objects — each is an independent instance
Car tesla = new Car("Tesla");
Car civic = new Car("Honda");

tesla.accelerate(60);
civic.accelerate(30);

tesla.printStatus(); // Tesla is going 60 km/h
civic.printStatus(); // Honda is going 30 km/h
04 · The core idea

The Four Pillars of OOP

Every OOP concept in Java branches out from these four ideas.

Bundle data + behavior, hide the internals.

Encapsulation means wrapping fields and the methods that operate on them inside a single class, and restricting direct access to the fields from outside. The class exposes only what's needed through public methods (getters/setters), while the actual data stays private.

Why it matters: Without it, any part of a program could reach in and corrupt an object's state directly. Encapsulation protects invariants — e.g. a bank balance can never be set to a negative number if the setter enforces that rule.

Think of a medicine capsule: the drug (data) is sealed inside, and you interact with it only through the outer shell (methods) — you never touch the raw powder directly.

privatebalancegetBalance()deposit()data hidden inside · access only through public methods
Encapsulation.java
public class BankAccount {
    // fields are private — hidden from outside
    private double balance;

    public BankAccount(double openingBalance) {
        this.balance = openingBalance;
    }

    // public methods control access to the data
    public double getBalance() {
        return balance;
    }

    public void deposit(double amount) {
        if (amount > 0) balance += amount;
    }

    public void withdraw(double amount) {
        if (amount > 0 && amount <= balance) {
            balance -= amount;
        } else {
            System.out.println("Invalid withdrawal");
        }
    }
}

// usage
BankAccount acc = new BankAccount(1000);
acc.deposit(500);
acc.withdraw(200);
System.out.println(acc.getBalance()); // 1300.0
// acc.balance = -50; // ❌ not allowed, balance is private
05 · Beyond the pillars

Object Relationships

How objects connect to each other — from a loose reference to full ownership.

Association

A general "uses-a" link. A Teacher teaches Students — neither owns the other's lifecycle.

class Teacher { Student student; }

Aggregation

A "has-a" relationship where the part can exist independently. A Department has Employees, but they still exist if the Department is deleted.

class Department { List<Employee> staff; }

Composition

Strong ownership — the part cannot exist without the whole. A House's Rooms disappear if the House is destroyed.

class House { private final Room room = new Room(); }
06 · Keywords that matter

static, final & the Object class

StaticFinalDemo.java
class Counter {
    static int count = 0;      // shared across all instances
    final String id;          // set once, never changed

    Counter() {
        count++;
        id = "COUNTER-" + count;
    }
}

Counter a = new Counter();
Counter b = new Counter();
System.out.println(Counter.count); // 2 — shared field
System.out.println(a.id);          // COUNTER-1
// a.id = "X"; // ❌ compile error — final cannot be reassigned
ObjectMethods.java
class Point {
    int x, y;
    Point(int x, int y) { this.x = x; this.y = y; }

    @Override
    public String toString() {
        return "Point(" + x + ", " + y + ")";
    }

    @Override
    public boolean equals(Object o) {
        if (!(o instanceof Point)) return false;
        Point p = (Point) o;
        return x == p.x && y == p.y;
    }

    @Override
    public int hashCode() {
        return Objects.hash(x, y);
    }
}

Point p1 = new Point(1, 2);
Point p2 = new Point(1, 2);
System.out.println(p1);            // Point(1, 2)
System.out.println(p1.equals(p2)); // true
07 · Quick reference

OOP Cheat Sheet

Every keyword you'll actually type, in one glance.

class

Blueprint for creating objects

object

Instance of a class, created with `new`

this

Refers to the current object instance

super

Refers to the immediate parent class

extends

Class inheritance (single, in Java)

implements

A class fulfilling an interface contract

abstract

Class/method with no full implementation

interface

Pure contract of method signatures

private

Accessible only within the same class

protected

Accessible in same package + subclasses

public

Accessible from anywhere

(default)

Accessible only within the same package

static

Belongs to the class, not any instance

final

Cannot be overridden / reassigned / extended

@Override

Marks a method as overriding a parent's

instanceof

Checks an object's runtime type

08 · Learning path

OOP Roadmap

Follow this order — each step builds on the last.

1

Classes & Objects

Fields, methods, `this`, constructors

2

Encapsulation

Access modifiers, getters/setters

3

Inheritance

extends, super, method overriding

4

Polymorphism

Overloading vs overriding, dynamic dispatch

5

Abstraction

Abstract classes vs interfaces

6

Object methods

toString(), equals(), hashCode()

7

Relationships

Association, aggregation, composition

8

static & final

Class-level members, immutability

9

SOLID principles

Writing OOP that scales cleanly

10

Design patterns

Singleton, Factory, Observer, Strategy

09 · In the real world

Where OOP actually gets used

Enterprise software

Banking, ERP & billing systems model real entities (Account, Invoice, Customer) directly as classes.

Android & desktop apps

UI components (Activity, View, Fragment) are all class hierarchies built on inheritance.

Game development

Player, Enemy, Weapon — polymorphism lets one update loop handle every game object uniformly.

Frameworks & libraries

Spring, Hibernate, and most Java frameworks rely on interfaces + abstraction to stay extensible.

Simulation systems

Traffic, physics, or crowd simulations map naturally onto interacting objects with their own state.

10 · Perspective

Features, theory & the future of OOP

Why OOP still matters in 2026

Functional programming and multi-paradigm languages have grown fast, but OOP hasn't gone anywhere — it's merged with them. Modern Java (records, sealed classes, pattern matching) keeps the object model but borrows functional ideas like immutability. Most large-scale systems — banking cores, Android, enterprise backends — are still organized around objects because teams of people reason about entities and responsibilities more easily than about pure data transformations.

The real cost of skipping it

Codebases that skip OOP discipline don't fail immediately — they fail slowly. A few global functions mutating shared state work fine for a weekend project, then become unmaintainable once five people touch the same file. Encapsulation and clear class boundaries are what let a team split a large system into pieces that can be worked on, tested, and reasoned about independently.

Where it's heading

The trend isn't 'OOP vs functional' — it's OOP absorbing functional safety nets. Java's records give you value-object style immutable classes with almost no boilerplate. Sealed classes make polymorphism exhaustive and compiler-checked. The four pillars remain the mental model; the syntax around them keeps getting leaner.

Take the notes with you

Everything on this page - pillars, diagrams, cheat sheet, roadmap - bundled into one file you can revisit anytime.