bhylu.com

Advertisements

Java Choose an Access Boundary

Access modifiers control where a declaration can be used. They help express a component boundary, but they are not a substitute for authorisation or a security boundary around hostile code.

Understand the idea

public exposes a member to permitted callers across packages. private restricts it to its declaring top-level class and its nested context. Package-private declarations have no access keyword and stay within the package. protected has package access plus subclass rules across packages; it does not simply mean public to all subclass objects. Also distinguish access modifiers from non-access modifiers such as static, final and abstract.

Run it locally

Use a local JDK 21 or newer. Save the complete example as Main.java in a separate lab folder, then compile and run it with the commands below. Java examples do not run in Bhylu’s browser playground. The -ea option enables assertion checks used by some lessons.

JDK and terminal setup

javac --release 21 -encoding UTF-8 -d out Main.java
java -ea -cp out Main

A worked example

Java 21+ · Main.java

public class Main {
    static final class CapacityRule {
        private final int limit = 8;
        public boolean accepts(int requested) { return requested > 0 && requested <= limit; }
    }

    public static void main(String[] args) {
        CapacityRule rule = new CapacityRule();
        System.out.println(rule.accepts(6));
    }
}

Expected output

true

The rule exposes a question rather than its internal limit field. final on the nested class prevents subclassing; private on the field controls access; public on the method advertises the operation. Those keywords solve different problems. In a multi-file project, the enclosing class and package must also make the type accessible to the intended caller.

Check the official Java documentation for detailed contracts and supported options.