EMZETT.
Login

Modifiers (Access Modifiers)

In short: Keywords that determine from where a class, method, or variable may be accessed — the technical basis for encapsulation.

In more detail: Typical levels are: public (accessible from anywhere), protected (only within the class and its subclasses), package-internal (only within the same module/package), and private (only within the class itself). Besides access modifiers, there are other modifiers like “final” (a value/class can no longer be changed or further inherited) or “static” (belongs to the class itself, not to an individual object).

In Depth

The visibility levels usually form a hierarchy from “most open” to “most strictly hidden”:

public class Account {
    private double balance;          // ONLY visible within this class
    protected String accountType;     // this class + subclasses
    String branch;            // package-internal (no keyword = "package-private")
    public String accountNumber;     // accessible from anywhere
}

The rule of thumb for good encapsulation is: as restrictive as possible, as open as necessary. Fields should be private by default and only made more visible if there’s a genuine, concrete reason for it — later OPENING an access is usually unproblematic (existing code keeps working), while later CLOSING an already-public access can break any code that already relies on it.

Besides pure access modifiers, there are other, orthogonal modifiers:

  • static: the member belongs to the class itself, not to an individual instance — all objects share the same value/method, a call needs no concrete object.
  • final: depending on context, this means “this variable can’t be changed after its first assignment”, “this method can’t be overridden in subclasses”, or “this class can’t be inherited further”.
  • abstract: a method with no concrete implementation, which a subclass must necessarily provide (see Abstraction).

These modifiers can usually be combined (public static final, for example, is the usual way to define a genuine, class-wide constant) — but not all combinations are meaningful or even allowed (a private abstract, for example, would mean a method has to be implemented but would simultaneously be invisible to subclasses — a logical contradiction most compilers reject).

See also: Encapsulation, Classes, Inheritance