Sub topic 3
Public, Protected, Package-Private, and Private
Java access modifiers control where code can use a class member. A member is a field, method, or constructor declared in a class. Access modifiers help you decide which parts of a class other code can use and which parts stay inside it.
Java has four access levels:
publicprotected- Package-private, written with no access modifier
private
This chapter focuses on access to members of ordinary classes. The same access levels can apply to some class declarations too, but class access has its own rules.
Start with the access context
To decide whether an access is allowed, look at the code that is trying to use the member. Its location is the access context.
A package is a named group of Java classes. For example, a class with the declaration package demo.inside; belongs to the demo.inside package.
The important questions are:
- Which class contains the code trying to use the member?
- Is that class in the same package as the member’s class?
- If it is in a different package, is it a subclass?
- Can the code access the class that contains the member?
A subclass is a class that extends another class. It can receive members from the class it extends, subject to Java’s rules.
The four access levels
The table gives a working guide for members of a class. It assumes the class containing the member is accessible.
| Member access | Same top-level class | Another top-level class in the same package | Subclass in a different package | Unrelated class in a different package |
|---|---|---|---|---|
| `public` | Yes | Yes | Yes | Yes |
| `protected` | Yes | Yes | Yes, with extra rules | No |
| Package-private | Yes | Yes | No | No |
| `private` | Yes | No | No | No |
A top-level class is a class declared outside any other class. The table distinguishes it from a nested class, which is declared inside another class.
For protected, a subclass in a different package has access, but not in every possible form. For example, the object used to reach the member can matter. The detailed cross-package rules are covered later.
Public
A public member can be used from other packages, as long as the code can access the class containing it and other applicable boundaries permit the access.
public class Counter {
public int value = 0;
}Here, value is a public field. Code that can access Counter can normally read or change that field directly.
Public access is useful when other code needs to use a member. It is also a broad choice: many classes may come to depend on that member.
Protected
A protected member is available:
- To code in the same package.
- To subclass code in a different package, subject to extra rules.
The first point is easy to miss. A class does not need to be a subclass to use a protected member in the same package.
Protected access is not the same as public access. An unrelated class in a different package cannot use the member just because it is protected.
Package-private
In an ordinary class, a field or method with no access modifier is package-private. Code in the same package can use it; code in a different package cannot.
public class Counter {
int value = 0;
}The field value has package-private access. There is no package-private keyword to write.
Package names must match exactly. For example, shop and shop.orders are different packages. A class in shop.orders does not get package-private access to members in shop.
Private
A private member can be used by code in the same top-level class, including its nested classes. Other top-level classes cannot use it directly, even when they are in the same package.
Private access is about the location of the code, not which object the member belongs to. For example, a method in Device can read a private field from another Device object. The method’s code is still inside Device.
Private does not mean that a value can never be observed. A public method might return a private value or use it to produce a result. The access modifier controls direct access to the member.
Worked example: access in two packages
This example uses three classes. Two are in the same package, and one is in a different package.
Create the folders and files shown below. Run the commands from the folder that contains the demo folder.
- Create a folder named
demo. - Inside it, create folders named
insideandoutside. - Save each file in the path shown above its code.
The class with four access levels
Save this as demo/inside/Device.java:
package demo.inside;
public class Device {
public String name = "Meter";
protected int signal = 7;
int units = 3;
private int calibration = 2;
public int adjustedReading(int raw) {
return raw + calibration;
}
public boolean hasSameCalibration(Device other) {
return calibration == other.calibration;
}
}The fields show all four access levels. The adjustedReading method can use calibration because the method is inside Device.
The hasSameCalibration method also reads other.calibration. That is allowed even though other is a different object: the code doing the reading is inside Device.
These fields are exposed this way to demonstrate access levels. In a real class, public fields deserve careful thought because other code can change them directly.
A different class in the same package
Save this as demo/inside/InsideDemo.java:
package demo.inside;
public class InsideDemo {
public static void main(String[] args) {
Device device = new Device();
System.out.println(device.name);
System.out.println(device.signal);
System.out.println(device.units);
System.out.println(device.adjustedReading(10));
System.out.println(device.hasSameCalibration(new Device()));
// System.out.println(device.calibration); // Does not compile
}
}InsideDemo is a different top-level class from Device, but both are in demo.inside. It can therefore use the public, protected, and package-private fields.
It cannot directly use the private calibration field. The last line is a comment, so Java does not run it. If you remove the comment marks from that line, the code will not compile.
Instead, InsideDemo can call adjustedReading. That public method uses calibration from inside Device and returns a result.
An unrelated class in a different package
Save this as demo/outside/OutsideDemo.java:
package demo.outside;
import demo.inside.Device;
public class OutsideDemo {
public static void main(String[] args) {
Device device = new Device();
System.out.println(device.name);
System.out.println(device.adjustedReading(10));
// System.out.println(device.signal); // Does not compile
// System.out.println(device.units); // Does not compile
// System.out.println(device.calibration); // Does not compile
}
}The import line lets this file use the short name Device for the class in demo.inside. An import does not grant extra access.
OutsideDemo is in a different package and is not a subclass of Device. It can use the public field and method, but it cannot directly use the other three fields.
Compile and run
A compiler is a tool that checks Java source code and produces files that Java can run. From the folder containing demo, compile the three files:
javac demo/inside/Device.java demo/inside/InsideDemo.java demo/outside/OutsideDemo.javaThen run the class in the same package as Device:
java demo.inside.InsideDemoIts output is:
Meter
7
3
12
trueRun the class in the other package:
java demo.outside.OutsideDemoIts output is:
Meter
12The commented-out lines describe access attempts that Java would reject. Access is checked when the code is compiled, even if a bad line would not be reached while the program runs.
How to check an access attempt
When you see an expression such as device.signal, use this process:
- Find the declaration of
signaland its access level. - Find the class containing the code that uses
signal. - Compare the packages of that class and the class declaring the member.
- If the member is
protectedand the access is from a subclass in another package, check the extra protected rules. - Make sure the containing class is accessible too.
For example, consider device.units in OutsideDemo:
unitshas no access modifier, so it is package-private.OutsideDemois indemo.outside.Deviceis indemo.inside.- The packages differ, so the access is not allowed.
The fact that OutsideDemo can create a Device does not give it access to every member of Device.
Common mistakes
Treating packages as folders with shared access
Folders usually help organize source files, but Java uses the package declarations to determine package membership. Two similarly named packages are still different packages.
For example, demo.inside and demo.inside.tools do not share package-private access.
Assuming an import changes access
An import helps code refer to a type by its short name. It does not turn a protected, package-private, or private member into a public one.
Assuming private means “this object only”
A method in a class can use that class’s private members on another object of the same class. The hasSameCalibration method showed this with other.calibration.
Assuming protected means “subclasses only”
Other classes in the same package can also use a protected member. The InsideDemo class used device.signal without extending Device.
Assuming public always means available everywhere
A member’s containing class must also be accessible. In some projects, a named module can add another boundary. A module is a named group of packages; it can limit which packages are available to other modules.
For now, remember that public is the broadest member access level, not a way to bypass every boundary around a class.
Choosing a starting level
Use the narrowest level that fits the intended use of the member:
- Choose
privatewhen the member is only for code inside the class and its nested classes. - Choose package-private when collaborating classes in the same package need direct access.
- Choose
protectedwhen same-package access and access for subclasses are both intended. - Choose
publicwhen code outside the package needs to use the member.
These are starting questions, not a rule that every field needs a matching public method. Later chapters examine how to choose the operations a class exposes and how those operations protect its state.
Exercises
Exercise
A class in package store declares int stock;. Can an unrelated class in store read stock directly? Can an unrelated class in store.reports do so?
Show answer
The class in store can, because stock is package-private. The class in store.reports cannot, because it is in a different package.
Exercise
In the worked example, why can InsideDemo read signal but not calibration?
Show answer
signal is protected, so another class in the same package can access it. calibration is private, so InsideDemo, a different top-level class, cannot access it directly.
Exercise
A class in another package imports Device. Does that import allow it to read units?
Show answer
No. The import allows use of the short class name; it does not change the package-private access of units.
Exercise
Change units in Device to public int units = 3;. After recompiling, could OutsideDemo read device.units?
Show answer
Yes. Device is accessible to OutsideDemo, and a public units field can be accessed from the other package.