Skip to content

Information Technology · Ch 2 — Programming

Access Specifiers and Encapsulation

2

Access Specifiers and Encapsulation

When a class has fields and methods, we usually do not want every other part of the program to reach in and change them freely. Java lets us control this with access specifiers (also called access modifiers) — keywords placed before a field, method or class to say who is allowed to use it.

The four levels of access

SpecifierAccessible fromMeaning in plain words
publicanywhereopen to every class in the program
privateonly the same classhidden; usable only inside its own class
protectedsame class, same package, and subclassesopen to the class, its package, and children (see Inheritance)
default (no keyword)same package onlypackage-private; the level you get when you write no specifier

private is the most restrictive and public the most open; protected and the default sit in between.

Encapsulation — the reason access specifiers exist

Encapsulation means wrapping the data (fields) and the code that uses it (methods) together in one class, and hiding the data from the outside. The standard technique is:

  1. make the fields private, so nothing outside can change them directly, then
  2. provide public methods — a getter to read a field and a setter to change it — so all access happens through code you control.
class Account {
    private double balance;              // hidden data

    public double getBalance() {         // getter
        return balance;
    }

    public void deposit(double amount) { // setter with a rule
        if (amount > 0) {                // guard: reject bad values
            balance = balance + amount;
        }
    }
}
``` …
Definition 1Access specifier

A keyword (public, private, protected, or none for default) that controls which parts of a program may use a fi …

Definition 2public

The least restrictive specifier — the member is accessible from any class anywhere …

Definition 3private

The most restrictive specifier — the member is accessible only inside i …

Definition 4protected

A member accessible within the same class, the same package, and any subclass …

Definition 5Encapsulation

Wrapping data and its methods in one class and hiding the data (usually by making fields private with public getters/setters) so the class …