Access Modifiers: Security Gates

Access Modifiers: Security Gates in Java: A bonded warehouse runs on passes, and the passes are checked at doors rather than argued about in offices.

The Analogy: The Pass System At A Bonded Whisky Warehouse

A bonded warehouse runs on passes, and the passes are checked at doors rather than argued about in offices. There are four kinds. The still-room key opens one room and is carried by the distiller who works that still. The site pass opens most internal doors and is issued to everybody whose desk is in this building. The trade pass belongs to staff from the wider company group at other sites, and opens racking doors -- with a condition. And the visitor gallery is glazed, signposted from the car park and open to anyone who walks in off the road. Nobody negotiates at the door; the lock either turns or it does not.

The still-room key and the site pass differ in kind, not in degree, and this is the part people get wrong. The still-room key is one lock and one room, and the site manager does not have it -- not because the manager is distrusted but because the key was cut for the person who works there. The site pass, by contrast, is not a rank at all. It is issued on the basis of where your desk is. The cleaner and the chief chemist carry the same site pass and it opens the same doors, because the question the lock asks is "is your desk in this building" and not "how senior are you".

The trade pass is the strange one, and it is stranger than it looks. A distiller from Site B, on group staff, holds a trade pass and it opens cask racking. But it opens the racking for casks standing in Site B's bays. Put that same person in front of a physically identical cask, same lock, same mechanism, belonging to Site A, and the pass is refused. The pass grants access to your own site's casks wherever you are, not to casks in general. It is a wider entitlement than the site pass -- it reaches across sites, which the site pass never does -- and simultaneously a fussier one.

The failure mode follows from how site passes are issued. They go by desk location, so a contractor who rents a desk in the building is handed one on his first morning and can walk into every room the site pass opens. Nobody decided to trust him; the rule simply described where he sits, and he satisfied it. The quieter version is a manager who needs one door opened for one visitor, issues a full site pass "just for today", and never gets it back -- so the visitor's entitlement outlives the reason for it by several years, and by the time anyone notices, three other people are relying on it.


Syntax or Core Structure

Java has four levels of access and only three keywords, because the middle level is spelled by writing nothing at all. The modifier goes at the front of a field, method, constructor or class declaration.

public class Vault {
    private int litres = 400;               // this class only
    int caskCount = 12;                     // no keyword: this package only
    protected String owner = "site-a";      // this package, plus subclasses anywhere
    public final String label = "VAT-7";    // everyone, and unchangeable

    private int gauge() {                   // an internal helper
        return litres / caskCount;
    }

    public int litresPerCask() {            // the published way to ask
        return gauge();
    }

    static class Sample {
        private String note = "clear";      // private to Sample...

        int length() {
            return note.length();
        }
    }

    public static void main(String[] args) {
        Vault v = new Vault();
        Sample s = new Sample();

        System.out.println("label     " + v.label);
        System.out.println("casks     " + v.caskCount);
        System.out.println("owner     " + v.owner);
        System.out.println("per cask  " + v.litresPerCask());
        System.out.println("litres    " + v.litres);   // legal: same class
        System.out.println("note      " + s.note);     // legal: same top-level class
        System.out.println("length    " + s.length());
    }
}

Output:

label     VAT-7
casks     12
owner     site-a
per cask  33
litres    400
note      clear
length    5

litresPerCask is the shape to notice. It is public and it does nothing except call gauge, which is private. That split is the entire technique: the arithmetic can change, be renamed, be replaced by a lookup table or be deleted, and no code outside this file can possibly have depended on it, because no code outside this file was ever able to name it. The public method is a promise; the private one is an implementation detail, and the keyword is what makes that distinction enforceable rather than aspirational.

The last two lines are the surprise. note is private to Sample, and main read it anyway. That is not a loophole -- private in Java means "accessible within the body of the enclosing top-level class", and Sample is nested inside Vault, so Vault and Sample are inside each other's privacy boundary. Two nested classes in one file are not isolated from one another, however private their members look.


Technical Depth: The Four Levels, The Rule About protected That Almost Nobody Knows, And What A Modifier Cannot Protect You From

The four levels, and why they are not a simple ladder

LevelSame classSame packageSubclass in another packageAnywhere else
privateYesNoNoNo
no keyword -- package-privateYesYesNoNo
protectedYesYesYes, with a restrictionNo
publicYesYesYesYes

Read the third row against the second. protected is wider than the default, not narrower, which is the opposite of what the word suggests and the opposite of the order most tutorials list them in. A protected member is visible to the whole package plus every subclass everywhere, and since anybody may write extends on a non-final class, protected is best understood as "public to anyone prepared to subclass me".

Row two has a second trap: there is no keyword for package access. A field with no modifier and a field whose modifier somebody forgot to type are byte-for-byte identical in the source, so the language gives you no way to record that the omission was deliberate. That is worth a comment on every package-private member you actually meant.

private is scoped to the top-level class, not to the class

The last two lines of the syntax output are the whole rule. Sample.note is private and Vault.main printed it, because the boundary the compiler enforces is the outermost class body in the file. Modern JVMs implement this with nest-based access control, and older ones generated hidden bridge methods, but the language rule has been the same since nested classes existed.

The practical consequence: putting two classes in one file to keep them "close" also means neither can hide anything from the other. If you want a real boundary, you need separate top-level classes, and if you want a boundary that survives someone adding a class next door, you need separate packages -- or a module.

private is the only reason a validation check can exist at all

public class Guarded {
    static class Loose {
        public int strengthAbv;                 // anyone, any value, no check possible
    }

    static class Tight {
        private int strengthAbv;

        void setStrengthAbv(int abv) {
            if (abv < 0 || abv > 96) {
                throw new IllegalArgumentException("abv out of range: " + abv);
            }
            this.strengthAbv = abv;
        }

        int strengthAbv() {
            return strengthAbv;
        }
    }

    public static void main(String[] args) {
        Loose l = new Loose();
        l.strengthAbv = -40;                    // nothing in the language can stop this
        System.out.println("loose     " + l.strengthAbv);

        Tight t = new Tight();
        t.setStrengthAbv(43);
        System.out.println("tight     " + t.strengthAbv());

        boolean blocked = false;
        try {
            t.setStrengthAbv(-40);
        } catch (IllegalArgumentException e) {
            blocked = true;
        }
        System.out.println("blocked   " + blocked);
        System.out.println("kept      " + t.strengthAbv());
    }
}

Output:

loose     -40
tight     43
blocked   true
kept      43

Loose is not badly written so much as unwritable: there is no line of code you could add to it that would reject minus forty, because assignment to a public field runs no code of yours. Tight gets to have a rule, and kept 43 is the point -- the rejected value did not partially land, so the object is still in the state it was in before the bad call. Encapsulation is not secrecy for its own sake; it is the mechanism that makes any invariant possible.

The protected restriction hardly anyone knows

Inside a subclass in a different package from its superclass, a protected instance member may only be accessed through an expression whose static type is that subclass or a subclass of it. Accessing it through a reference of the superclass type does not compile, even though you are inside a subclass and the member is right there.

// File 1 -- package site.core
package site.core;

public class Vault {
    protected String owner = "site-a";
}

// File 2 -- package site.branch
package site.branch;

import site.core.Vault;

public class Branch extends Vault {
    void mine() {
        System.out.println(this.owner);       // legal: through Branch
    }

    void sibling(Branch other) {
        System.out.println(other.owner);      // legal: static type is Branch
    }

    void foreign(Vault any) {
        System.out.println(any.owner);        // does NOT compile
    }
}

The compiler rejects the third method with a message of the form "owner has protected access in site.core.Vault". The rule exists so that a subclass cannot use its own inheritance as a lever to reach into unrelated instances of its parent: Branch may handle Branch objects, not every Vault in the program. Two footnotes -- protected static members are exempt from the restriction, and none of this applies while the subclass is in the same package, which is why this rule is invisible in single-package examples and lands as a shock in real projects.

An override may widen access, never narrow it

public class Narrow {
    static class Gate {
        protected String open() {
            return "gate";
        }
    }

    static class Wide extends Gate {
        @Override
        public String open() {                  // protected -> public is fine
            return "wide";
        }
    }

    public static void main(String[] args) {
        Gate g = new Wide();
        System.out.println("via Gate  " + g.open());
        System.out.println("via Wide  " + new Wide().open());
    }
}

Output:

via Gate  wide
via Wide  wide

Both lines print wide because the override wins regardless of which reference type you call through -- that is overriding, and unlike overloading it does consult the object. Writing String open() in Wide instead, dropping to package access, fails to compile with "attempting to assign weaker access privileges". The reason is substitutability: code holding a Gate was promised it could call open(), and a subclass is not allowed to withdraw a promise its supertype made.

What access modifiers do not protect you from

ThreatStopped?Why
A colleague calling a helper you never meant to publishYesprivate is checked at compile time, every time
Someone adding a class to your package to read package-private membersNoPackage membership is declared by the author of the new file, not granted by you
Reflection reading or writing a private fieldNot by defaultsetAccessible(true) works unless a module, a security policy or a record forbids it
A subclass overriding behaviour your own methods depend onNo, unless the method is finalAccess and overridability are independent axes
A caller mutating the object your public getter returnedNoThe field stayed private; the object it pointed at was handed over
Anyone at all reading the bytecode or the sourceNoModifiers are a design tool, not a confidentiality mechanism

The last two rows are the ones that cost money. A modifier constrains names, not objects: private List<String> extras guarantees that nobody else can rebind the field, and guarantees nothing whatsoever about the list. The Real World Example below is a class that gets every modifier right and leaks anyway for exactly that reason.


Real World Example: A Cask Register Where Every Modifier Is Chosen Deliberately And It Leaks Anyway

This class uses all four levels on purpose. Nothing in it is a mistake of ignorance: the fields are private, the helper is private, the constant is public because callers need it, and the counter with no modifier is a test hook. It still hands a caller the keys to its own internals, and it does so through a method that looks entirely reasonable.

import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

public class Warehouse {
    public static final int MAX_CASKS = 6;        // callers need the limit

    private final String site;                     // nobody else's business
    private final List<Integer> litres = new ArrayList<>();
    protected int rejected;                        // for subclasses... in theory
    int attempts;                                  // package access: a test hook

    public Warehouse(String site) {
        this.site = site;
    }

    public boolean store(int litresInCask) {
        attempts++;
        if (litresInCask <= 0 || litres.size() >= MAX_CASKS) {
            rejected++;
            return false;
        }
        litres.add(litresInCask);
        return true;
    }

    public int caskCount() {
        return litres.size();
    }

    public int totalLitres() {
        int sum = 0;
        for (int l : litres) {
            sum += l;
        }
        return sum;
    }

    // The leak: public, and it hands back the private list itself.
    public List<Integer> casks() {
        return litres;
    }

    private int mean() {
        return litres.isEmpty() ? 0 : totalLitres() / litres.size();
    }

    public String summary() {
        return String.format(Locale.ROOT,
                "%-8s casks %d  litres %4d  mean %3d  rejected %d",
                site, litres.size(), totalLitres(), mean(), rejected);
    }

    public static void main(String[] args) {
        Warehouse w = new Warehouse("site-a");

        int[] deliveries = {200, 190, 0, 205, 198, 195, 201, 199};
        for (int d : deliveries) {
            w.store(d);
        }

        System.out.println(w.summary());
        System.out.println("attempts  " + w.attempts);
        System.out.println("count     " + w.caskCount());
        System.out.println("total     " + w.totalLitres());

        // No modifier is violated on either of the next two lines.
        List<Integer> handed = w.casks();
        handed.clear();
        handed.add(-999);

        System.out.println(w.summary());
        System.out.println("after     " + w.caskCount());
        System.out.println("negative  " + w.totalLitres());
        System.out.println("max       " + MAX_CASKS);
    }
}

Output:

site-a   casks 6  litres 1189  mean 198  rejected 2
attempts  8
count     6
total     1189
site-a   casks 1  litres -999  mean -999  rejected 2
after     1
negative  -999
max       6

Each level is doing a job. site and litres are private because no caller needs them and, more importantly, because store can only be the sole gatekeeper of what enters the list if nothing else can reach the list -- the litresInCask <= 0 check has meaning for exactly as long as that field stays private. MAX_CASKS is public because a caller who wants to avoid a rejection has to be able to ask what the limit is; publishing the number is cheaper than making people discover it by failing. And attempts has no modifier at all, which is the one genuinely good use of package access: a test class in the same package can read it without a getter, and no code outside the package can see it exists.

rejected is protected, and it should not be. The intent is readable -- a subclass such as a customs-reporting warehouse would want the count -- but the effect is that anyone in any package can write four lines of extends and then both read and assign it. protected is not a narrower public; on a non-final class it is public to anyone willing to subclass, and it grants write access as freely as read access. The alternative costs one line: make the field private and add public int rejected(). Subclasses get everything they actually needed, and nobody gets to set the number to zero.

Now read the second summary line, and notice that no modifier was violated to produce it. Every field is still private. store is still the only method that appends. And the register is reporting one cask holding minus 999 litres, because casks() returned the actual ArrayList and the caller emptied it and put nonsense in. This is the distinction from the table above made concrete: private protects the variable, guaranteeing nobody else can rebind litres, and says nothing at all about the object litres points at. The fix is one word -- return List.copyOf(litres); -- and it closes the hole completely.

The honest limits, and the design flaw is the combination rather than either half. This class advertises encapsulation and then provides two independent routes around it, which is worse than a class with frankly public fields, because a caller reasonably concludes that caskCount() and totalLitres() report something the class controls. A class should be sealed or it should be a plain data holder; the middle position invites people to depend on an invariant it does not keep. Beyond that: mean() is correctly private but does integer division, so 1189 litres over 6 casks reports 198 and the missing litre is unreachable by any caller; MAX_CASKS is a public static final int with a compile-time constant value, so it is inlined into every class that reads it and raising the limit means rebuilding all of them, not just this file; store returns a boolean that main ignores, so eight deliveries produced six casks and two silent failures with only rejected to hint at it; and attempts and rejected are unsynchronised, so two lorries unloading on two threads will lose counts with no error anywhere.


Common Mistakes

  1. Public fields. public int strengthAbv cannot be validated, cannot be renamed without breaking callers, and cannot later become a computed value. It is the one modifier choice that closes every future door.
  1. Treating package access as "nearly private". Anyone who writes package your.package; at the top of a new file joins your package and can read those members. It is a convention between colleagues, not a boundary, unless a module seals it.
  1. Assuming protected is narrower than the default. It is wider: package plus every subclass everywhere. If your goal was "a bit less than public", the default is what you wanted.
  1. Making a field protected so a subclass can read it. You have granted the world write access as well. Use a protected or public accessor and keep the field private.
  1. Returning a live mutable field from a getter. return litres; undoes every private in the class. Return List.copyOf(...), an unmodifiable wrapper, or a defensive copy.
  1. Trying to narrow access in an override. Turning a public method into protected in a subclass fails with "attempting to assign weaker access privileges"; a subclass cannot withdraw a promise its supertype made.
  1. Reading private as "this class". It means "this top-level class", so nested classes in one file can see straight through each other. Move code to separate files when you want a real boundary.
  1. Omitting a modifier and never noticing. Because package access has no keyword, a forgotten private and a deliberate package-private member look identical. Comment the deliberate ones.
  1. Putting private or protected on a top-level class. Only public or nothing is legal there, one public class per file, and its name must match the filename -- three separate compile errors that all read as if you have mistyped the class name.

Best Practices

  • Start at private and widen only for a caller who exists. Widening access is a one-word change; narrowing it breaks every user you have, so the default should be the tightest thing that compiles.
  • Keep every field private, without exception. Publish behaviour, not state: caskCount() can become a cached value, a database count or a computed figure, and public int caskCount can only ever be a field.
  • Comment the members you deliberately left package-private. int attempts; // package access: read by WarehouseTest turns a missing keyword into a recorded decision.
  • Prefer a protected accessor to a protected field. The subclass gets the value; nobody gets to assign it; and you can change how it is computed later.
  • Copy or wrap collections and arrays at every public boundary, in both directions. This is the single most common way a well-encapsulated class leaks, and the fix is always one line.
  • Make classes final unless you have designed for inheritance. The moment a class can be subclassed, its protected members and its overridable methods become a contract you cannot change without breaking somebody.
  • Keep the public surface as small as you can live with. Every public method is a promise across every future version; every one you do not add is a decision you have not yet had to commit to.
  • Never treat modifiers as a security control. They are a compile-time design discipline. Reflection, a class dropped into your package, and anyone with the jar all go straight past them -- put secrets somewhere else entirely.

Practice Exercises

  1. The Sealed Register. Fix casks() twice: once returning List.copyOf(litres) and once returning Collections.unmodifiableList(litres). Rerun the leak in main for both and show that the second summary line is now identical to the first. Then describe the one behavioural difference between the two fixes -- what happens in each version if store is called after a caller is already holding the returned list.
  1. The Protected Leak. In a second package, write a subclass of Warehouse whose only method sets rejected to 0, and prove it compiles and works. In the same class, add a method that takes a plain Warehouse parameter and reads rejected from it, and record the exact compiler error. Then change rejected to private with a public int rejected() getter and report which of your two methods still compiles and why.
  1. The Four Doors. Build two packages. In the first, put a class with four members, one at each access level. Then try to read all four from each of: the same class, a second class in the same package, a subclass in the second package through this, that same subclass through a parameter of the superclass type, and an unrelated class in the second package. Tabulate which of the twenty attempts compile, and write one sentence on the result that surprised you most.