Sub topic 8
Protected Access Across Package Boundaries
A protected member gives a subclass access to part of its parent class. But when the subclass is in a different package, Java places an extra limit on how the subclass can use that member.
A package is a way to group Java classes. A subclass is a class that extends another class, called its superclass. A member is a field, method, or constructor belonging to a class.
In this chapter, you will see why a subclass can use a protected method on itself and on another suitably typed subclass object, but not on just any superclass object.
The working rule
Suppose a class named Device declares a protected method. If code is in the same package as Device, it can use that method. The code does not have to be in a subclass.
Across a package boundary, the rules are narrower:
- The access must be inside a subclass of Device.
- For an instance field or instance method, the object used for access must also meet a type rule.
An instance member belongs to an object. For example, a signal field can hold a different value for each Device object.
Inside a subclass named SmartDevice, the type rule allows access through:
- The current object, written as this, or without a name before the member.
- The superclass form, written as super.
- A reference whose type is SmartDevice or a subclass of SmartDevice.
A reference is a value that lets code work with an object. A reference typed only as Device does not meet the last rule, even if it happens to refer to a SmartDevice object.
This chart checks protected access. The classes and members must also be otherwise available to the code.
Build an example
You need a Java Development Kit installed to compile and run the example. Create a project folder containing two folders named devices and apps.
Put the following code in devices/Device.java:
package devices;
public class Device {
protected static final int DEFAULT_SIGNAL = 5;
protected int signal = DEFAULT_SIGNAL;
protected Device() {
}
protected void resetSignal() {
signal = 0;
}
public int readSignal() {
return signal;
}
}Device has a protected field named signal and a protected method named resetSignal. Its public method, readSignal, lets other code read the signal.
DEFAULT_SIGNAL is a static field. A static field belongs to the class rather than to a particular object. The word final means this field cannot be assigned a new value after it is set.
The protected Device constructor will also help us see a constructor rule later.
Now put this code in apps/SmartDevice.java:
package apps;
import devices.Device;
public class SmartDevice extends Device {
public SmartDevice() {
super();
}
public void resetSelf() {
super.resetSignal();
}
public void resetPeer(SmartDevice peer) {
peer.resetSignal();
}
void checkReferences(
Device baseView, SmartDevice peer, OtherDevice sibling) {
peer.resetSignal();
peer.signal = 3;
// baseView.resetSignal(); // Does not compile.
// sibling.resetSignal(); // Does not compile.
}
public static void main(String[] args) {
SmartDevice first = new SmartDevice();
SmartDevice second = new SmartDevice();
Device baseView = second;
System.out.println("Default: " + Device.DEFAULT_SIGNAL);
System.out.println("Second before: " + baseView.readSignal());
first.resetPeer(second);
System.out.println("Second after: " + baseView.readSignal());
first.resetSelf();
System.out.println("First after: " + first.readSignal());
// baseView.resetSignal(); // Does not compile.
// Device direct = new Device(); // Does not compile.
}
}
class OtherDevice extends Device {
}
class DeviceVisitor {
int read(SmartDevice device) {
// device.resetSignal(); // Does not compile.
return device.readSignal();
}
}The import statement lets SmartDevice use the name Device for the class in the devices package. The word extends makes SmartDevice a subclass of Device.
OtherDevice is another subclass of Device. It is not a subclass of SmartDevice. DeviceVisitor is not a subclass of Device.
From the project folder, compile and run the example:
javac devices/Device.java apps/SmartDevice.java
java apps.SmartDeviceYou should see:
Default: 5
Second before: 5
Second after: 0
First after: 0The lines marked “Does not compile” start with comment marks, so Java ignores them. Later, you can remove the marks one line at a time to test the rules.
Access through the current object
SmartDevice can use the protected resetSignal method it receives from Device. In resetSelf, it uses the superclass form:
super.resetSignal();The word super lets the subclass refer to its superclass implementation. SmartDevice could also call resetSignal() or this.resetSignal() in this example.
The important point is that the code is inside SmartDevice, a subclass of Device. The access works across the package boundary because SmartDevice is using the protected method on its own object.
In the program, first.resetSelf() changes the signal of first from 5 to 0.
Access through another subclass reference
A subclass can also access a protected instance member through some other objects. In resetPeer, the peer reference has type SmartDevice:
peer.resetSignal();That access is allowed inside SmartDevice. The type of peer is SmartDevice, which meets the cross-package rule.
This is why first.resetPeer(second) can reset second. The object being changed is not the current object, first. It is another SmartDevice, passed to the method as peer.
The checkReferences method also shows access to the protected field through a SmartDevice reference. It can call peer.resetSignal() and assign a value to peer.signal.
A reference typed as a subclass of SmartDevice would also meet the type rule. For example, if a class SpecialDevice extended SmartDevice, a reference typed as SpecialDevice could be used this way inside SmartDevice.
Why a Device reference is different
Look at these two lines in main:
SmartDevice second = new SmartDevice();
Device baseView = second;Both references point to the same object. But they have different types:
- second is declared as SmartDevice.
- baseView is declared as Device.
Java checks protected access using the type of the reference expression. It does not grant access just because the object happens to be a SmartDevice.
Therefore, inside SmartDevice, the commented call baseView.resetSignal() does not compile. The reference is typed as Device, not SmartDevice or a subclass of SmartDevice.
The call baseView.readSignal() does compile because readSignal is public. It does not need the protected instance access rule.
A sibling subclass is not enough
OtherDevice also extends Device. It is a sibling of SmartDevice: both have Device as their superclass, but neither extends the other.
Inside SmartDevice, the commented call sibling.resetSignal() does not compile. The sibling reference has type OtherDevice, not SmartDevice or a subclass of SmartDevice.
Being in the same package as SmartDevice does not change that result. The protected method is declared in Device, which is in the devices package. The code making the call is in the apps package.
This distinction is easy to miss. For the package check, start with the package of the class that declares the protected member.
What an unrelated class can do
DeviceVisitor is in the apps package, just like SmartDevice. Its read method takes a SmartDevice reference. Still, the commented call to device.resetSignal() does not compile.
DeviceVisitor is not a subclass of Device. It cannot use the cross-package subclass access rule, even though:
- It is in the same package as SmartDevice.
- The reference is typed as SmartDevice.
- SmartDevice can use the protected method.
DeviceVisitor can call device.readSignal(), because that method is public.
A protected member is therefore not part of the general public interface merely because a public subclass can use it.
Protected constructors across packages
Device has a protected constructor. The SmartDevice constructor calls it with super():
super();That call is allowed. It runs the Device constructor as part of creating a SmartDevice.
However, the commented expression new Device() in SmartDevice does not compile. It tries to directly create a Device using its protected constructor from a different package.
These are different actions:
- super() constructs the superclass part of the new SmartDevice.
- new Device() directly creates a Device.
The example still allows Device baseView = second. That line does not construct a Device. It stores a reference to the SmartDevice that was already created.
Protected static members
The example also uses Device.DEFAULTSIGNAL inside SmartDevice. That access is allowed: SmartDevice is a subclass, and DEFAULTSIGNAL is protected.
The extra reference-type rule discussed earlier applies to protected instance fields and methods. It does not apply in the same way to a static member, because a static member belongs to the class, not to a particular object.
The access still has to be allowed in its context. For example, DeviceVisitor cannot use Device.DEFAULT_SIGNAL merely because it is in the same package as SmartDevice.
Check the cases
In this table, the first four accesses occur inside SmartDevice, which is in a different package from Device.
| Access | Allowed? | Reason |
|---|---|---|
| super.resetSignal() | Yes | SmartDevice uses the superclass form on its own object. |
| peer.resetSignal(), where peer is SmartDevice | Yes | The reference type is SmartDevice. |
| baseView.resetSignal(), where baseView is Device | No | The reference type is not SmartDevice or its subclass. |
| sibling.resetSignal(), where sibling is OtherDevice | No | OtherDevice is not SmartDevice or its subclass. |
| device.resetSignal() inside DeviceVisitor | No | DeviceVisitor is outside the declaring package and is not a Device subclass. |
| Device.DEFAULT_SIGNAL inside SmartDevice | Yes | It is a protected static member accessed within a subclass. |
| super() inside the SmartDevice constructor | Yes | It calls the protected superclass constructor while constructing a SmartDevice. |
Try the compiler
Try removing the comment marks from baseView.resetSignal() in main. Run the compile command again. Java should report an access error.
Put the comment marks back, then try sibling.resetSignal() in checkReferences. That call also fails, but for a slightly different reason: OtherDevice is a subclass of Device, yet it is not a subclass of SmartDevice.
Finally, restore the comment marks and compile the program again. Compiler wording can vary between Java versions, so focus on which line fails and why.
Choose protected members carefully
Protected access is useful when a superclass is designed to let subclasses build on its behavior. It is broader than access for the superclass alone: subclasses in other packages can use the member too.
That also means a protected field can be changed by subclass code. For example, SmartDevice can assign to peer.signal. If Device needs to keep signal within a certain range, direct protected field access makes that rule harder to enforce.
A superclass can instead keep a field private and offer a protected method that checks values before changing it. Choose protected access when subclass access is intentional, not simply to make a field easy to reach.
Exercise
Inside SmartDevice, why does peer.resetSignal() compile when peer is typed as SmartDevice, but baseView.resetSignal() fails when baseView is typed as Device?
Show answer
Across the package boundary, the reference for protected instance access must be typed as SmartDevice or a subclass of it. Device is a superclass, so the Device-typed reference does not meet that rule.
Exercise
DeviceVisitor is in the same package as SmartDevice. Why can it call readSignal but not resetSignal on a SmartDevice?
Show answer
readSignal is public. resetSignal is protected and declared in Device in a different package; DeviceVisitor is not a Device subclass.
Exercise
Why can the SmartDevice constructor call super(), while new Device() fails inside SmartDevice?
Show answer
super() calls the protected Device constructor as part of constructing a SmartDevice. new Device() directly tries to create a Device using that protected constructor across the package boundary.