Chapter 4 · Simulation

Access Modifiers and Encapsulation

← Chapter 4

Packages and classesclick a class or a member

Accessing class

    same classsame packagesubclass*other package

    * subclass in another package; protected only via inheritance: interest ✓, h.interest ✗

    Correct 0 / 0

    Access Modifiers and Encapsulation

    Purpose: see how the compiler checks which class may access a field or method. The bank package has Account and Teller; the app package has TermAccount, a subclass of Account, and the unrelated Customer.

    How to use it

    1. Access control: click the accessing class and a member of Account in the diagram (or choose them from the lists above). On the right you see the accessing class's code, the compiler's verdict and a table of the four access levels; the table fills in as you explore.
    2. In the subclass (and in Account itself) there are two forms: directly (interest, that is this.interest) or through another object (h.interest).
    3. Encapsulation: because balance is private, an Account object can be changed only by its own methods. Enter an amount and try the methods; invalid amounts are rejected, and h.balance = m does not compile at all.
    4. Try it yourself: in the access view, predict whether a random line compiles; in the encapsulation view, predict the balance after the operation.

    The four access levels

    ModifierSame classSame packageSubclass (other package)Other package
    public✓✓✓✓
    protected✓✓✓*✗
    (none) package access✓✓✗✗
    private✓✗✗✗
    • * A subclass in another package can access a protected member only through its own objects (or objects of its own subtypes): interest = 0.05; compiles, h.interest = 0.05; (where h is an Account) does not.
    • private is class-level: code inside Account can also access the h.balance field of another Account object.
    • private members are not inherited: for isValid(10) inside TermAccount the compiler says cannot find symbol.
    • Encapsulation: fields are private, behaviors are public. The value is read with a getter (getBalance()); changes are made only through methods that check the rules (deposit, withdraw), so the object never falls into an invalid state (e.g. a negative balance).

    bank/Account.java

    Every access combination in the diagram was verified by compiling the four classes together with javac --release 8; the error messages shown are javac's real messages. The operations in the encapsulation view were compared against Java programs run with the same class.

    Related slides: Chapter 4.2 · Encapsulation (Access Modifiers, The Four Access Levels, Accessor Methods, Package Access) and Chapter 4.3 · Inheritance (The protected Access Level).