Skip to content

Try “polymorphism”, “TCP handshake” or “git rebase”.

    Java / Object-Oriented Programming

    Encapsulation

    Encapsulation — keeping an object's data private and allowing access only through methods that enforce its rules.

    Chapter 1 of 125 min read

    Start With the Problem#

    StudyBuddy's quizzes have three kinds of question:

    • multiple choice — correct if the student picks option A;

    • true/false — correct if the student says false;

    • short answer — correct if the student types "water", ignoring case and spaces.

    They share a lot (every question has text and points, and can be graded) but differ in exactly one thing: how to check an answer. Without OOP you'd write:

    Java
    if (type.equals("mcq")) { ... } else if (type.equals("tf")) { ... } else if (type.equals("short")) { ... }

    — copied into the grading code, the display code, the export code… Add a fourth type ("fill in the blank") and you must find and edit every copy. Miss one and it breaks.

    And there's a second problem: StudyBuddy has an AI-credit balance per student. Right now any code anywhere can write account.credits = -500;. Nothing protects the rule "credits can never go negative".

    Object-oriented programming is the set of ideas that solves both: bundle data with the rules that protect it, and let different kinds of things share one interface while each behaves in its own way.

    The Plain Picture#

    An ATM. You can't open it and take money out of the drawer. You can only use its buttons: check balance, withdraw. The ATM checks every request — "is the amount positive? is there enough money?" — before touching the cash inside. The drawer is hidden; the buttons are the only way in.

    The Real Names#

    • Encapsulation = keeping an object's data private and allowing access only through methods that enforce its rules.

    • The rules that must always be true about an object are its invariants — e.g. "credits ≥ 0".

    • Access modifiers control who can see a field, method or class:

    ModifierVisible toTypical use
    privateonly code inside the same classfields (almost always)
    (none) — "package-private"classes in the same packagehelpers internal to a package
    protectedsame package and subclasses (Ch 2)things subclasses need
    publiceveryonethe object's intended "buttons"

    Under the Hood#

    Java
    class Account {
        private int credits; // hidden: nobody outside can touch it
    
        Account(int credits) {
            if (credits < 0) throw new IllegalArgumentException("credits must be >= 0"); // guard the invariant from the start
            this.credits = credits;
        }
    
        int getCredits() {
            // a GETTER: read access only
            return credits;
        }
    
        boolean spend(int amount) {
            // the only way to change credits — with rules
            if (amount <= 0 || amount > credits) return false;
            credits -= amount;
            return true;
        }
    }
    Java
    Account acc = new Account(10);
    
    System.out.println(acc.spend(4) + " " + acc.spend(100) + " " + acc.getCredits()); // true false 6
    
    new Account(-5); // rejected: credits must be >= 0
    
    acc.credits = 5; // compile error: credits has private access in Account

    (throw new IllegalArgumentException(...) stops the constructor with an error — exceptions are taught in Exceptions and Generics.)

    Why this matters: because credits can only change through spend, the rule "never negative" is checked in one place and is always true. If the rule changes ("allow a small overdraft for premium students"), you edit one method.

    Getters and setters: a getter returns a field (getCredits); a setter changes one (setName). Don't generate a setter for every field automatically — that throws encapsulation away. Offer meaningful operations (spend, refund) instead of raw setters.

    Check yourself

    4 questions
    1

    What is encapsulation, in one sentence?

    Show answer

    Hiding an object's data and exposing only methods that enforce its rules.

    2

    What's an invariant? Give one for StudyBuddy.

    Show answer

    A rule that must always hold for the object — e.g. "credits are never negative".

    3

    Order the four access levels from most to least restrictive.

    Show answer

    private → package-private → protected → public.

    4

    Why is spend(int amount) better than setCredits(int c)?

    Show answer

    spend enforces the business rules in one place; a setter lets callers put the object into any state, including invalid ones.