In Java-style object-oriented programming, access modifiers determine which classes may access an inherited member. Public is the least restrictive, private is the most restrictive, while protected and default access provide intermediate levels of visibility.
How each modifier works
When a subclass extends a superclass, it does not automatically gain direct access to every superclass member. Accessibility depends on both the modifier and whether the subclass is in the same package as the superclass.
| Access modifier | Where the member is accessible | Effect on a subclass |
|---|---|---|
public | From every class | Directly accessible in all subclasses, including those in other packages |
protected | Within the same package and in subclasses | Directly accessible to subclasses, including subclasses in other packages |
| default (no modifier) | Only within the same package | Accessible to a subclass only if that subclass is in the same package |
private | Only within the class that declares it | Not directly accessible in the subclass |
For example:
class Account {
public String owner;
protected double balance;
int branchCode; // default access
private String password;
}
class SavingsAccount extends Account {
void display() {
System.out.println(owner); // allowed
System.out.println(balance); // allowed
System.out.println(branchCode); // allowed only in same package
// System.out.println(password); // not allowed
}
}
A subclass can interact with a private field indirectly through inherited public or protected methods, such as getPasswordStatus(). This supports encapsulation, because the superclass controls how its internal data is accessed or modified.
A common misconception is that protected means “accessible only by subclasses.” In Java, protected members are also accessible to non-subclass classes in the same package. Another misconception is that access modifiers change the inheritance relationship; they change member visibility, not whether one class extends another.
IB exam technique
For B3.2 HL questions, identify the member’s declaring class, modifier, package, and accessing class. When asked to explain, state both whether access is permitted and why; do not simply say that the member is “inherited.”