Sub topic 2
Access Modifiers for Classes and Members
Access Modifiers for Classes and Members
An access modifier controls where Java code can use a class, field, method, or constructor. A field stores data, a method performs an action, and a constructor sets up a new object.
A package is a group of related classes. The four access levels are:
| Access level | Where it can be used |
|---|---|
| `public` | From other code, if the class itself is accessible |
| `protected` | In the same package and in subclasses, with extra rules across packages |
| Package-private | In the same package; write no modifier |
| `private` | Within the same top-level class and its nested classes |
A subclass is a class based on another class. A nested class is declared inside another class. Fields, methods, constructors, and nested classes can use any of the four levels. A top-level class, which is not inside another class, can only be public or package-private.
Choosing a Class's Public API
A class’s public API is the set of things other code can use, such as its public constructors and methods. Keep this set small: offer useful actions, but hide details that callers do not need.
Encapsulation means keeping data and the operations on it together while controlling how that data changes. Access modifiers help enforce that control.
Protecting State with Constructors and Methods
An invariant is a rule that must stay true for an object. For a bank account, one rule might be that its balance cannot be negative.
Save this example as BankAccount.java:
public class BankAccount {
private long balance;
public BankAccount(long openingBalance) {
if (openingBalance < 0) {
throw new IllegalArgumentException("Negative balance");
}
balance = openingBalance;
}
public long getBalance() {
return balance;
}
public void deposit(long amount) {
if (amount < 0 || amount > Long.MAX_VALUE - balance) {
throw new IllegalArgumentException("Invalid deposit");
}
balance += amount;
}
}
class Demo {
public static void main(String[] args) {
BankAccount account = new BankAccount(10);
account.deposit(5);
System.out.println(account.getBalance());
}
}Run javac BankAccount.java, then java Demo. The result is 15.
Other code cannot write directly to balance. The constructor rejects a negative opening balance. deposit rejects negative amounts and amounts that would exceed the largest long value. Invalid input causes an error.
Access in Inheritance
Inheritance lets a subclass build on another class. A subclass cannot directly use a private field of its parent class. It can use accessible methods instead. For example, a BankAccount subclass can call getBalance() to read the balance.
Exercise
Why does the example make balance private instead of public?
Show answer
A public field could be changed directly to a negative value. A private field forces other code to use the checked operations.