Sub topic 9
Apply Access Rules Across Packages
This chapter assumes you can write a Java class with fields, methods, and constructors, and that you know the four access modifiers by name. You also need to be able to compile and run a Java program from the command line. Here you will see how those modifiers behave when a subclass lives in a different package from its superclass.
Why packages matter for inheritance
A package is a named group of related classes. The package line at the top of a file puts the class in that group. A class's full name is the package plus the class name, such as com.shop.base.Account.
Inheritance lets a subclass reuse its superclass's members, but access modifiers decide what the subclass is allowed to touch. The rules depend on where the subclass lives. A subclass in the same package as its superclass can see more than a subclass in another package. Most access bugs in inheritance come from forgetting this difference.
The four access levels
Every member (field, method, or constructor) has one of four access levels:
publicmeans any code can use the member.protectedmeans code in the same package can use it. Subclasses in other packages can also use it, but only in a limited way (see below).- Package-private means code in the same package can use it. You get this level by writing no modifier at all.
privatemeans only code inside the same class can use it.
The table summarizes who can access each level.
| Modifier | Same class | Same package | Subclass in another package | Any other code |
|---|---|---|---|---|
| `public` | Yes | Yes | Yes | Yes |
| `protected` | Yes | Yes | Yes (with a restriction) | No |
| none (package-private) | Yes | Yes | No | No |
| `private` | Yes | No | No | No |
A worked example with two packages
Create this folder layout. The com/shop/base folder holds the superclass. The com/shop/app folder holds the subclass and the program that runs it.
// File: com/shop/base/Account.java
package com.shop.base;
public class Account {
public String owner;
protected double balance;
int branchCode = 101;
private String pin = "1234";
public Account(String owner, double balance) {
this.owner = owner;
this.balance = balance;
}
public String describe() {
return owner + " has " + balance;
}
protected void audit() {
System.out.println("Audit: " + owner);
}
void internalCheck() {
System.out.println("Branch " + branchCode);
}
private boolean pinMatches(String attempt) {
return pin.equals(attempt);
}
public boolean verify(String attempt) {
return pinMatches(attempt);
}
}Account has one member at each access level: owner is public, balance is protected, branchCode is package-private, and pin is private. Next comes the subclass, which lives in a different package.
// File: com/shop/app/SavingsAccount.java
package com.shop.app;
import com.shop.base.Account;
public class SavingsAccount extends Account {
public SavingsAccount(String owner, double balance) {
super(owner, balance);
}
public void addInterest(double rate) {
balance += balance * rate;
audit();
}
public double peerBalance(SavingsAccount other) {
return other.balance;
}
}SavingsAccount imports Account because the two classes are in different packages. Inside addInterest, the subclass reads and changes balance and calls audit(). Both are protected, so this is allowed. Finally, a class that runs the program:
// File: com/shop/app/App.java
package com.shop.app;
public class App {
public static void main(String[] args) {
SavingsAccount s = new SavingsAccount("Mia", 100.0);
s.addInterest(0.05);
System.out.println(s.describe());
System.out.println(s.owner);
System.out.println(s.verify("1234"));
}
}Compile and run from the folder that contains com:
javac -d out com/shop/base/Account.java com/shop/app/SavingsAccount.java com/shop/app/App.java
java -cp out com.shop.app.AppThe output is:
Audit: Mia
Mia has 105.0
Mia
trueThe -d out option tells javac to place the compiled classes in an out folder that mirrors the package structure. The -cp out option tells java where to find them.
What the subclass cannot touch
The subclass cannot use branchCode, internalCheck(), or pin. Suppose you add these lines to SavingsAccount:
// Each of these lines fails to compile inside SavingsAccount.
int b = branchCode;
internalCheck();
String p = pin;The compiler reports errors like these:
branchCode is not public in Account; cannot be accessed from outside package
internalCheck() is not public in Account; cannot be accessed from outside package
pin has private access in AccountPackage-private and private members are not usable by the subclass, so the subclass has no way to reach them directly. The verify method shows the usual fix: the superclass offers a public method, and the private details stay hidden.
The App class is also outside the inheritance chain. It is in a different package and is not a subclass, so s.balance fails there with the message balance has protected access in Account.
Protected has a special rule
Protected is the most confusing level. People often say "protected means subclasses can use it", but the full rule has a catch. In a different package, a subclass can use a protected member only through a reference of its own type (or a subtype of it).
That is why peerBalance in SavingsAccount works. The parameter is a SavingsAccount, so other.balance is allowed. Now try changing the parameter type to Account:
// This method fails to compile inside SavingsAccount.
public double peerBalance(Account other) {
return other.balance;
}The compiler says balance has protected access in Account. The reason is that other might be some different subclass of Account, such as a CheckingAccount from a third package. One subclass should not be able to read the protected data of an unrelated sibling. If both classes were in the same package, this restriction would not apply, because protected includes package access.
Private members still exist in the object
A subclass does not inherit private members, but they are still part of every object. When you create a SavingsAccount, the object holds a pin field because Account declared it. Only the code of Account can read it. This is why verify works when called on a SavingsAccount: it runs inside Account, where pin is visible.
Put simply, "not inherited" means "not accessible by name in the subclass". It does not mean the data is missing.
Access and overriding
When a subclass overrides a method, the new version cannot be less visible than the original. A public method must stay public. A protected method may be overridden as protected or public. Making it more visible is allowed, and making it less visible is a compile error. The next chapters cover the full override rules.
Package-private methods add a twist. A subclass in a different package cannot see them, so a method with the same name and parameters in that subclass does not override anything. It is a new, unrelated method. This is one more reason to use @Override: the compiler will tell you when you did not actually override.
// File: com/shop/app/CheckingAccount.java
package com.shop.app;
import com.shop.base.Account;
public class CheckingAccount extends Account {
public CheckingAccount(String owner, double balance) {
super(owner, balance);
}
@Override
public void audit() {
System.out.println("Checking audit: " + owner);
}
}This compiles because audit() goes from protected to public, which widens access. If you removed public and wrote void audit(), the compiler would reject it for narrowing access. If you put @Override on a method named internalCheck(), the compiler would also reject it, because the superclass method is invisible from this package.
Common mistakes
- Assuming
protectedlets any code in a subclass read the member through anyAccountreference. In another package, you need a reference of the subclass type. - Forgetting that no modifier means package-private, not "visible to subclasses". A subclass in another package cannot see it.
- Trying to access a private field of the superclass by name in the subclass. Use a public or protected method instead.
- Narrowing access when overriding, such as turning
publicintoprotected. - Writing a method that looks like an override of a package-private method in another package. It does not override, and
@Overridewould flag it.
Exercise
In the example above, SavingsAccount is in com.shop.app and Account is in com.shop.base. Would this.branchCode compile inside SavingsAccount? What would change if SavingsAccount were moved into the package com.shop.base?
Show answer
It would not compile in com.shop.app, because branchCode is package-private and the subclass is in a different package. If SavingsAccount were moved into com.shop.base, it would compile, because package-private members are visible to every class in the same package.
Exercise
A class Vault in package com.shop.app is not a subclass of Account. It contains this code: Account a = new Account("Sam", 50.0); System.out.println(a.balance);. Does it compile? Explain.
Show answer
It does not compile. balance is protected. Vault is in a different package and is not a subclass of Account, so it has neither package access nor subclass access. Only public members of Account are visible to it.
Exercise
SavingsAccount has a method double compare(Account other) { return balance - other.balance; }. Which part fails to compile, and what is one way to fix it?
Show answer
other.balance fails because, in a different package, protected access is allowed only through a reference of the subclass type, and other is an Account. One fix is to change the parameter type to SavingsAccount. Another fix is to add a public double getBalance() method to Account and call other.getBalance().