Information Technology · Ch 2 — Programming
Access Specifiers and Encapsulation
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
| Specifier | Accessible from | Meaning in plain words |
|---|---|---|
public | anywhere | open to every class in the program |
private | only the same class | hidden; usable only inside its own class |
protected | same class, same package, and subclasses | open to the class, its package, and children (see Inheritance) |
| default (no keyword) | same package only | package-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:
- make the fields
private, so nothing outside can change them directly, then - provide
publicmethods — 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;
}
}
}
``` …
A keyword (public, private, protected, or none for default) that controls which parts of a program may use a fi …
The least restrictive specifier — the member is accessible from any class anywhere …
The most restrictive specifier — the member is accessible only inside i …
A member accessible within the same class, the same package, and any subclass …
Wrapping data and its methods in one class and hiding the data (usually by making fields private with public getters/setters) so the class …