Access Modifiers

OOP · lesson 19 of 43 · 3 min read

What private, package-private, protected and public actually let through.

Open this lesson in the learning hub

Key points

  • private: this class only. public: everyone, forever. Those are the two you should reach for.
  • No modifier at all means package-private: visible to any class in the same package, invisible outside it.
  • protected means package-private plus subclasses in other packages. It is a wider door than most people think.
  • Start every member private and widen only when a caller genuinely needs it. Widening is easy, narrowing breaks people.
  • A protected field is part of your public API: every subclass anywhere can now depend on it.
  • Nested classes in the same file can see each other private members, which is why this demo uses separate classes.

Example

public class Main {
    public static void main(String[] args) {
        Vault v = new Vault();
        // System.out.println(v.secret);   // will not compile: private to Vault
        System.out.println(v.report());    // private is reachable from inside Vault
        System.out.println(v.pkg);         // same package, so this is allowed
        System.out.println(v.prot);
        System.out.println(v.open);
        System.out.println(new Branch().show());
    }
}

class Vault {
    private   String secret = "private   -> Vault itself only";
              String pkg    = "package   -> anything in this package";
    protected String prot   = "protected -> package plus subclasses";
    public    String open   = "public    -> everybody, forever";

    private String peek() { return secret; }

    String report() { return peek(); }
}

class Branch extends Vault {
    // 'secret' is invisible here: a subclass does not inherit private members.
    String show() { return "subclass sees -> " + prot + " | " + open; }
}

Default to private and widen one notch at a time, only when someone needs it.

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.