Sub topic 4
Access Modifiers for Classes and Members
A Java program can contain many classes, but not every class needs to be available everywhere. The same is true of the fields, methods, and constructors inside a class.
An access modifier is a word that controls where code can use a declaration. A declaration introduces something, such as a class or method. Choosing an access level helps show which parts of a class are meant for other code and which parts are for internal use.
In this chapter, you will compare access rules for classes and their members. You will also run a small program with code in two packages.
Classes and members have separate access levels
A member is something declared inside a class, such as a field, method, or nested class. A nested class is a class declared inside another class. Constructors also have access levels, although Java does not call them members.
The access level of a class and the access level of something inside it are separate choices. For example:
- A class can be public while one of its fields is private.
- A class can be available only within its package while a method inside it is public.
A package is a named group of Java classes. A class in another package cannot normally use the second class by its name, even though the method is public. The class itself is not available there.
Think of access as two questions:
- Can this code use the class?
- If so, can this code use the particular field, method, constructor, or nested class?
Access for top-level classes
A top-level class is a class declared outside every other class. Java gives a top-level class two access choices.
| Declaration | Access |
|---|---|
| `public class Counter` | Code in other packages can use the class, subject to any module rules. |
| `class CounterNote` | Only code in the same package can use the class by its name. |
The second choice has no access modifier. It is called package-private access.
A top-level class cannot be declared private or protected. Those modifiers can be used for certain declarations inside a class, but not for a top-level class.
File names
With the Java compiler used in this chapter, a public top-level class must be in a file with the same name as the class. For example, public class Counter must be in Counter.java. The capitalization must match.
A source file can contain at most one public top-level class. It can also contain package-private top-level classes. In the example below, CounterNote is package-private and appears in Counter.java alongside Counter.
Access for members and constructors
Members have more access choices than top-level classes. Constructors can also use these four access levels.
| Access level | Where it allows access |
|---|---|
| `public` | From other code that can use the class, subject to any module rules. |
| `protected` | From the same package. It can also allow access in a subclass in another package, with additional rules. |
| Package-private | From the same package. Write no access modifier for this choice. |
| `private` | From within the declaring class. Related nested code can also use private declarations. |
A subclass is a class that extends another class. The rules for protected access across packages need special care; they are covered separately. For this chapter, notice that code in the same package can use a protected member.
Access depends on the code that is trying to use something, not on who created the object. For example, one object does not gain permission to read a private field simply because it holds a reference to another object.
A class can, however, use its own private fields on another object of the same class. The access check is about where the code is written.
Constructors can limit object creation
A constructor is the part of a class used to create and set up an object. Its access level can differ from the class’s access level.
For example, a public class with a package-private constructor can be named outside its package, but code there cannot call that constructor. A private constructor is even more restrictive. Code inside the class can call it, but ordinary outside code cannot.
A class does not become easy to create from everywhere just because the class itself is public. Check the constructor too.
Access for nested classes
A nested class is a member of its enclosing class. An enclosing class is the class that contains the nested declaration. Unlike a top-level class, a nested class can be declared public, protected, package-private, or private.
A public nested class can be named by outside code only when that code can also use the enclosing class through which it names the nested class. For example, if Outer is not accessible, code in another package cannot use Outer.Inner through that name, even if Inner is public.
The nested class’s own members have their own access levels too. A public nested class could have a private field or a package-private constructor.
Static and non-static nested classes
The word static is not an access modifier. For a nested class, it means that an object of that nested class does not need an object of the enclosing class.
A non-static nested class is also called an inner class. An object of an inner class is tied to an object of the enclosing class. That inner object can use fields of its enclosing object, including private fields.
The example below includes both kinds:
Labelis a public static nested class.Viewis a public inner class.Formatteris a private static nested class used insideCounter.
Worked example
This example uses two packages: shop and app. The shop package provides a public Counter class. It also has a package-private class named CounterNote.
You need a Java Development Kit, or JDK, installed to run the example. The JDK includes javac, the Java compiler, and java, the command that runs the program.
Create a working folder. Inside it, create src/shop and src/app. Then add the following three files.
The class being used
Save this file as src/shop/Counter.java:
package shop;
public class Counter {
private int value;
public Counter(int startingValue) {
value = startingValue;
}
public int getValue() {
return value;
}
public String describe() {
return Formatter.format(value);
}
void reset() {
value = 0;
}
protected String kind() {
return "counter";
}
public static class Label {
private final String text;
public Label(String text) {
this.text = text;
}
public String getText() {
return text;
}
}
public class View {
public int read() {
return value;
}
}
private static class Formatter {
private static String format(int number) {
return "Count: " + number;
}
}
}
class CounterNote {
String message() {
return "Package note";
}
}The package shop; line places both top-level classes in the shop package.
The value field is private, so code outside Counter cannot read or write it directly. The public getValue method gives outside code a way to read it. The public describe method uses Formatter, which outside code cannot name because it is private.
The reset method has no access modifier, so it is package-private. The kind method is protected, so code in the same package can use it too.
Label has a public constructor and a public method. Its text field is private. View reads the private value field of its enclosing Counter object.
Code in the same package
Save this file as src/shop/CounterCheck.java:
package shop;
public class CounterCheck {
public static void main(String[] args) {
Counter counter = new Counter(4);
counter.reset();
System.out.println(counter.kind() + ": " + counter.getValue());
CounterNote note = new CounterNote();
System.out.println(note.message());
}
}CounterCheck is in the shop package. It can call reset and kind. It can also use CounterNote and its package-private message method.
It still cannot directly use counter.value: being in the same package does not make a private field available to every class in that package.
Code in another package
Save this file as src/app/Main.java:
package app;
import shop.Counter;
public class Main {
public static void main(String[] args) {
Counter counter = new Counter(2);
System.out.println(counter.describe());
Counter.Label label = new Counter.Label("orders");
System.out.println(label.getText());
Counter.View view = counter.new View();
System.out.println("View: " + view.read());
}
}The import line lets this file use the short name Counter for shop.Counter. An import is a way to refer to a class without writing its full package name each time. It does not give code extra access.
Main can use Counter because the class is public. It can call the constructor and describe because they are public too.
For the static nested class, the program creates a label with new Counter.Label(...). For the inner class, it creates a view with counter.new View(). The counter before new tells Java which Counter object the view belongs to.
Compile and run
From the working folder, run:
javac -d out src/shop/Counter.java src/shop/CounterCheck.java src/app/Main.java
java -cp out shop.CounterCheck
java -cp out app.MainThe -d out option tells the compiler to put its output in the out folder. The -cp out option tells Java where to find that compiled code.
The first run prints:
counter: 0
Package noteThe second run prints:
Count: 2
orders
View: 2Checking what another class can use
Consider Main, which is in the app package and is not a subclass of Counter.
| Attempt from `Main` | Result | Reason |
|---|---|---|
| Create `new Counter(2)` | Allowed | Both the class and constructor are public. |
| Call `counter.getValue()` | Allowed | The method is public. |
| Read `counter.value` | Not allowed | The field is private. |
| Call `counter.reset()` | Not allowed | The method is package-private, and `Main` is in another package. |
| Call `counter.kind()` | Not allowed | The method is protected; this call is from unrelated code in another package. |
| Name `Counter.Formatter` | Not allowed | The nested class is private. |
| Name `shop.CounterNote` | Not allowed | The top-level class is package-private. |
Each “not allowed” attempt would cause a compile error. The compiler checks access before the program runs.
A common mistake is to see a public method and assume anyone can call it. First check whether the calling code can use the class that provides the method. Also pay attention to types in the method’s inputs and result. A type may be a class such as Counter.Label. If a public method uses a type that callers cannot access, those callers may be unable to name that type or use its members.
Another mistake is to think that an import changes access. It only gives a convenient name to something the code is already allowed to use.
Choosing an access level
Start by asking which code needs to use the declaration.
- Use
publicfor a class, constructor, or member that other packages need to use. - Use package-private access when code in the same package needs it, but outside code does not.
- Use
privatefor details used only inside the class and its related nested code. - Use
protectedwhen same-package access or subclass access is intended. Check the cross-package rules before relying on it.
These choices are independent. A public class does not require public fields, and a public nested class does not require a public constructor. Make each declaration as accessible as its intended use requires.
Exercise
In the worked example, why can CounterCheck call reset, while Main cannot?
Show answer
reset is package-private. CounterCheck is in the shop package, but Main is in the app package.
Exercise
If a public nested class has a private constructor, can ordinary code in another class create it by calling that constructor?
Show answer
No. The nested class may be public, but its private constructor is not accessible to ordinary outside code.
Exercise
Is static an access modifier? How does Main create a Counter.View instead of a Counter.Label?
Show answer
No. Label is static and uses new Counter.Label(...). View is an inner class, so it uses an enclosing object: counter.new View().