Sub topic 3
Protected Access Across Package Boundaries
A package is a group of Java classes. A protected member can be used by classes in its own package. It can also be used by a subclass, a class that extends another class, in a different package.
Across packages, there is a limit: the subclass cannot use a protected member through a reference typed as the parent class.
Create folders named p and q. Save these files in them.
// p/Box.java
package p;
import java.util.ArrayList;
import java.util.List;
public class Box {
private final List<String> items;
public Box(List<String> items) {
this.items = new ArrayList<>(items);
}
protected void add(String item) {
items.add(item);
}
public List<String> getItems() {
return new ArrayList<>(items);
}
}// q/SpecialBox.java
package q;
import java.util.ArrayList;
import java.util.List;
import p.Box;
public class SpecialBox extends Box {
public SpecialBox(List<String> items) {
super(items);
}
@Override
public void add(String item) {
super.add(item);
}
void tryOther(Box other) {
// other.add("coin"); // Does not compile.
}
public static void main(String[] args) {
List<String> source = new ArrayList<>();
source.add("pen");
SpecialBox box = new SpecialBox(source);
source.add("pencil");
box.getItems().clear();
box.add("book");
System.out.println(box.getItems());
}
}Run these commands from the folder containing p and q:
javac p/Box.java q/SpecialBox.java
java q.SpecialBoxThe output is [pen, book]. super.add(item) works because it calls the parent’s protected method on this object. The commented-out call does not work: other is typed as Box and is in another package.
Access Rules for Overridden Methods
Overriding is replacing an inherited method with a subclass’s version. SpecialBox overrides add and makes it public.
An override may widen access, as this one does. It cannot narrow access: changing the override to private would cause a compile error.
Defensive Copying and Mutable State
A mutable list can be changed after it is created. A defensive copy is a separate copy made to prevent unwanted changes.
Box copies the list passed to its constructor and returns another copy from getItems. Adding to source or clearing the returned list therefore does not change the box.
Public Access and Module Exports
A module is a group of packages. In a named module, declaring a class public is not always enough for other modules to use it. The module can declare exports p; in module-info.java to share its public types. The other named module must also be allowed to read it, often through a requires declaration. Code on the classpath does not need these exports.
Exercise
Why would other.add("coin") fail, and why does clearing the list from getItems() leave the box unchanged?
Show answer
The protected method is accessed through a Box-typed reference across packages. getItems() returns a separate copy, so clearing it does not clear the box.