Class Member Access Modifiers

You’d think we’re done, but we’re not.  Although the Pair class is visible to the Driver class, the class members (fields and constructor) are not.

Class members can have one of 4 access modifiers: private, no-modifier, protected and public.  Below is a table that describes where members are accessible for each access modifier.

SubclassNoNoYesYes

Private No Modifier Protected Public
Different package No No No Yes
Subclass No No Yes Yes
Same package No Yes Yes Yes
Same class Yes Yes Yes Yes

Lets summarize the member access modifiers.

  1. If a member is public, it is accessible everywhere
  2. If a member is protected, it is accessible within the class’ package and from within subclasses in other packages.
  3. If a member has no modifier, it is only accessible within the class’ package.
  4. If a member is private, it is only accessible inside the same class.

Exposing Components in your API

If you’re creating a class that is intended to be used by other classes in other packages, the components that you want to expose must be public.

For example, if we declare a class named Pair in a particular package (e.g. repo.a1) and create a driver in a different package (e.g. default) and assuming the driver is not a subclass of Pair, in order for driver to access the methods and constructor in Pair, they must be declared public.  To prevent access to the fields from outside the class, we set them to private.

package repo.a1; 

public class Pair {
    private int x;
    private int y;

    public Pair(int x, int y) {
        this.x = x;
        this.y = y;
    }

    public int getX() { return x; }
    public int getY() { return y; }
}

Recommendations

Bloch recommends the following:

  • Item 13: Minimize the accessibility of classes and members

“The single most important factor that distinguishes a well-designed module from a poorly designed one is the degree to which the module hides its internal data and other implementation details from other modules.  A well-designed module hides all of its implementation details, cleanly separating its API from its implementation.  Modules then communicate only through their APIs and are oblivious to each other’s inner workings.  This concept, known as information hiding or encapsulation, is one of the fundamental tenets of software design [Parnas72]”.

  • Item 14: In public classes, use accessor methods, not public fields
  • Item 15: Minimize mutability

© 2017 – 2019, Eric. All rights reserved.