The Four Pillars of OOP

OOP · lesson 31 of 43 · 3 min read

Abstraction, encapsulation, inheritance and polymorphism, named once and shown in one small program.

Open this lesson in the learning hub

Key points

  • Abstraction is deciding what a caller needs to know. Everything else stays behind the interface, unsaid.
  • Encapsulation is keeping the data and the rules that protect it in one class, with the field private.
  • Inheritance is a subtype reusing and specialising a supertype. Use it for a genuine IS-A, not to borrow a method.
  • Polymorphism is one call site with many bodies: the object decides, not the variable you happen to hold.
  • Abstraction is the pillar people skip. Ask what a caller must know, then delete everything else from the public API.

Example

import java.util.List;

public class Main {

    // ABSTRACTION: the caller sees one question - can you open?
    interface Lock {
        boolean unlock(String code);
    }

    // ENCAPSULATION: the pin is private, and only this class ever compares it.
    static class PinLock implements Lock {
        private final String pin;
        private int attempts;

        PinLock(String pin) { this.pin = pin; }

        @Override public boolean unlock(String code) {
            attempts++;
            return pin.equals(code);
        }

        int attempts() { return attempts; }
    }

    // INHERITANCE: everything a PinLock does, plus an attempt limit.
    static class LimitedLock extends PinLock {
        private final int max;

        LimitedLock(String pin, int max) { super(pin); this.max = max; }

        @Override public boolean unlock(String code) {
            if (attempts() >= max) return false;      // locked out for good
            return super.unlock(code);
        }
    }

    public static void main(String[] args) {
        // POLYMORPHISM: one loop, one call, two different bodies.
        List<Lock> doors = List.of(new PinLock("1234"), new LimitedLock("1234", 1));

        for (Lock door : doors) {
            System.out.println("wrong code -> " + door.unlock("0000"));
            System.out.println("right code -> " + door.unlock("1234"));
        }
        // The caller never saw a pin, an attempt counter, or a class name.
    }
}

Abstraction decides what to show; the other three decide how it behaves.

This is a reading copy. The full lesson — with the visual explainer, the interactive lab and a Run button for the code — lives in the OOP course, and every lesson in it is listed on the OOP contents page.