Sub topic 11
Package-private and protected access
This chapter assumes you can write a class with fields and methods, use extends and super(...), and compile with javac. You should also know public and private and how a package declaration places a class in a package. Here you will learn how the two middle access levels, package-private and protected, depend on package membership.
The four access levels
Java has four access levels for class members (fields, methods, constructors, nested types). Only two of them are decided by the package.
| Modifier | Same class | Same package | Subclass in another package | Any other class |
|---|---|---|---|---|
| `private` | yes | no | no | no |
| none (package-private) | yes | yes | no | no |
| `protected` | yes | yes | yes, with restrictions | no |
| `public` | yes | yes | yes | yes |
Top-level classes have only two choices: public or package-private. A public top-level class must live in a file with the same name. Package-private top-level classes can't be imported from other packages at all.
Package-private: the default
If you write no modifier, the member is package-private. Only code in the same package can see it. It is often called "default access", but the language specification doesn't use that term, and the word default is a separate keyword in switch and interfaces.
package com.example.shop.model;
class PriceFormatter {
static String format(double price) {
return String.format("%.2f", price);
}
}PriceFormatter is a helper that the model package keeps to itself. Other packages can't import it, so you can change or delete it without breaking outside code. Package-private access lets you share code between classes in a package without adding it to the package's public API.
Packages are not hierarchical
The name com.example.shop.model looks like a child of com.example.shop. For access purposes it is not. Two packages are either the same package or unrelated, and no access exists between them.
com.example.shop.Maincan't use package-private members ofcom.example.shop.model.- A class in
com.example.shop.model.internalcan't use package-private members ofcom.example.shop.model.
Importing com.example.shop.* does not bring in com.example.shop.model either. Dots in package names help you organize and name things, and they grant no access.
What the compiler says
Suppose Main in com.example.shop imports com.example.shop.model.PriceFormatter. It fails with an error like this:
Main.java:3: error: PriceFormatter is not public in com.example.shop.model; cannot be accessed from outside packageIf the class is public but the method is package-private, the message says the method "is not public in ... cannot be accessed from outside package".
protected: package access plus subclasses
A protected member is visible to:
- all code in the same package, exactly like package-private, and
- subclasses in any package, with a restriction explained below.
The extra reach over package-private is that a subclass can use the member even when it lives in another package. Here is a base class that uses both levels.
package com.example.shop.model;
public class Product {
private final String name;
private final double price;
public Product(String name, double price) {
this.name = name;
this.price = price;
}
public String getName() {
return name;
}
public double getPrice() {
return price;
}
protected double discountRate() {
return 0.0;
}
String internalCode() {
return name.toUpperCase();
}
public double finalPrice() {
return price * (1 - discountRate());
}
}discountRate() is a hook for subclasses. internalCode() is package-private, so only the model package can call it.
Access from the same package
A class in com.example.shop.model can call both methods on any Product, because protected includes package access.
package com.example.shop.model;
public class ProductAudit {
public static String describe(Product p) {
return p.internalCode() + " rate=" + p.discountRate();
}
}Access from a subclass in another package
Book lives in a different package and extends Product.
package com.example.shop.catalog;
import com.example.shop.model.Product;
public class Book extends Product {
public Book(String name, double price) {
super(name, price);
}
@Override
protected double discountRate() {
return 0.10;
}
public static boolean sameRate(Book a, Book b) {
return a.discountRate() == b.discountRate();
}
}This compiles. Book can override discountRate() and call it on Book references. It still can't call internalCode(), because that method is package-private and Book is in another package. Inheritance does not carry package-private members across packages.
The restriction: the reference must be your own type
Outside the package, a subclass may use a protected member only through a reference whose type is the subclass itself (or one of its subclasses). Adding this method to Book fails.
static double peek(Product other) {
return other.discountRate();
}error: discountRate() has protected access in ProductThe reason is that Book has no right to look inside an arbitrary Product, which might be a different subclass written by someone else. It may use the inherited part only on its own kind of object. The same rule applies to fields. The compiler checks the static type of the expression, not the runtime object.
Constructors and static members
- A protected constructor can be called from another package only through
super(...)or an anonymous subclass expression.new Product("x", 1)from another package is rejected if the constructor is protected. - A protected static member can be used from a subclass in another package by simple name or as
Product.helper(). The "own type" restriction applies only to instance members.
Running the example
Add a main class that uses the pieces.
package com.example.shop.catalog;
public class BookDemo {
public static void main(String[] args) {
Book b = new Book("Java Basics", 20.0);
System.out.printf("%.2f%n", b.finalPrice());
}
}Compile all files with the output directory mirroring the packages, then run by fully qualified name.
javac -d out src/com/example/shop/model/Product.java \
src/com/example/shop/model/ProductAudit.java \
src/com/example/shop/catalog/Book.java \
src/com/example/shop/catalog/BookDemo.java
java -cp out com.example.shop.catalog.BookDemoThe output is 18.00. finalPrice() is public, so BookDemo can call it. It calls the overridden discountRate() through dynamic dispatch, so the book's 10% discount applies.
Gotchas and edge cases
- Overriding can't reduce access. An override must be at least as accessible as the method it overrides.
Bookcould widenprotected discountRate()topublic, but it can't narrow it to package-private orprivate. - A package-private method can't be overridden from another package. A same-named method in a subclass in another package is a new method, not an override.
@Overridethere produces a compile error, so always use the annotation. - Interface members are implicitly public. Implementing a method of an interface requires
publicin the class, and omitting it is a common error. - Package membership comes from the declaration. The directory layout is only a convention that tools rely on. Two classes are in the same package if they both declare the same package name and are loaded by the same class loader. This is why a package split across JARs may behave oddly, and why modules forbid it.
- protected is weaker than it looks. Anyone can write
package com.example.shop.model;in their own source and gain access to your protected and package-private members, unless a sealed JAR or a module prevents it. Don't rely on these levels for security. - Reflection can bypass these levels.
setAccessible(true)works unless a module restricts it.
Choosing a level
Use the narrowest level that works.
- Start with
private. - Widen to package-private when another class in the same package needs it. This is the right level for helpers and shared internals.
- Use
protectedonly for members that you intend subclasses to use or override, such as template-method hooks. Treat them as part of your public contract, because subclasses outside your control depend on them. - Use
publicfor the API that every user of the package should see.
Exercise
In package a, class Base has a protected void run(). In package b, class Child extends Base has a method void test(Base other) { other.run(); }. Does it compile? Does it compile if the parameter type is Child?
Show answer
With Base other it does not compile, because outside the package a subclass may use a protected member only through a reference of its own type (or a subtype). With Child other it compiles, since the reference is of type Child.
Exercise
Class Util in com.example.shop.model has a package-private static method clean(). Why can't com.example.shop.model.internal.Reader call it, even though the package names share a prefix?
Show answer
Packages aren't hierarchical. com.example.shop.model.internal is a different package from com.example.shop.model, so package-private access doesn't apply between them. clean() would need to be public, or Reader would need to move into com.example.shop.model.
Exercise
Subclass Book in another package defines double discountRate() (no modifier) to override protected double discountRate() in Product. What happens, and what is the fix?
Show answer
It fails to compile because an override can't have weaker access than the method it overrides. The fix is to declare it protected or public.