Sub topic 7
Control Method Access
An access modifier is a word in a method declaration that controls which code can call the method. Java has three method access modifiers: public, protected, and private. A method can also have no access modifier.
Access control helps you offer a simple way to use a class while keeping its internal steps separate. For example, a library card might let users record a visit but keep the step that logs the visit private.
The four access levels
A class is a blueprint for objects. A package is a named group of related Java classes. The class that declares a method is the declaring class.
| Method access | Declaring class | Other class in same package | Subclass in another package | Other class in another package |
|---|---|---|---|---|
| `public` | Yes | Yes | Yes | Yes |
| `protected` | Yes | Yes | Yes, with a rule for instance methods | No |
| No modifier | Yes | Yes | No | No |
| `private` | Yes | No | No | No |
This table assumes the caller can access the declaring class. The protected rule appears later in this chapter. There is also a special case for nested classes, which are classes declared inside other classes: they can share access to private members with their enclosing class.
Public
A public method can be called from other packages, provided the caller can also access its class. Use it for an action that outside code is meant to use.
A class must also be accessible. Making a method public does not make its class public.
Private
A private method is for internal work. Other ordinary classes cannot call it, even if they are in the same package. A subclass also cannot call it directly.
A private method can help split a larger task into smaller steps without making every step available to callers.
No modifier
A method with no access modifier has package-private access. It can be called by code in the same package, but not from another package.
Do not write the word default for this access level. In a method declaration, package-private access is shown by leaving out the access modifier.
Protected
A protected method can be called by code in the same package. It can also be used by a subclass in another package, subject to a rule described below.
A subclass is a class built from another class. It can use accessible methods of that other class. For example, a student card can be a special kind of library card.
Build a small example
This example uses all four access levels. It has two packages: library and visitors.
You need a Java Development Kit, or JDK, installed to compile and run it. Compiling means checking and translating source code into a form Java can run.
Create these folders in a working directory:
mkdir -p src/library src/visitorsSave each class in the file shown above it. The file name must match its public class name.
The library card
Save this as src/library/MemberCard.java:
package library;
public class MemberCard {
private int visits = 0;
public void recordVisit() {
visits++;
logVisit();
}
private void logVisit() {
System.out.println("Visits: " + visits);
}
void resetVisits() {
visits = 0;
}
protected void showWelcome() {
System.out.println("Welcome to the library.");
}
}The first line puts the class in the library package. The class itself is public, so code in another package can use it.
The card has four methods with different access levels:
recordVisitis public. Outside code can ask a card to record a visit.logVisitis private. It is an internal step called byrecordVisit.resetVisitshas no modifier. Other classes inlibrarycan call it.showWelcomeis protected. Classes inlibraryand suitable subclasses can use it.
The visits field is also private. A field is a variable stored in an object. Code outside MemberCard cannot change this field directly.
A class in the same package
Save this as src/library/Desk.java:
package library;
public class Desk {
public static void prepare(MemberCard card) {
card.resetVisits();
card.showWelcome();
}
}Desk can call both resetVisits and showWelcome because it is in the same package as MemberCard. It cannot call the private logVisit method.
prepare is a static method, so the example calls it through the class name, Desk. Its access modifier is still public.
A subclass in another package
Save this as src/visitors/StudentCard.java:
package visitors;
import library.MemberCard;
public class StudentCard extends MemberCard {
public void startVisit() {
showWelcome();
recordVisit();
}
}The import line lets this file use the name MemberCard for the class in the other package. The word extends makes StudentCard a subclass of MemberCard.
StudentCard can call showWelcome on itself because it is a subclass. It can call recordVisit because that method is public. It cannot call resetVisits: that method is package-private, and StudentCard is in a different package.
Run the example
Save this as src/visitors/Main.java:
package visitors;
import library.Desk;
public class Main {
public static void main(String[] args) {
StudentCard card = new StudentCard();
card.startVisit();
Desk.prepare(card);
card.recordVisit();
}
}From the working directory, compile and run the files:
javac -d out src/library/MemberCard.java src/library/Desk.java src/visitors/StudentCard.java src/visitors/Main.java
java -cp out visitors.Mainjavac is the Java compiler. The -d out option puts the compiled files in the out folder. The java command runs the program; -cp out tells it where to find those files.
The output is:
Welcome to the library.
Visits: 1
Welcome to the library.
Visits: 1Here is what happens:
startVisitshows a welcome, then records the first visit.Desk.prepareresets the count and shows another welcome.recordVisitadds one visit to the reset count.
The private logVisit method prints the count each time recordVisit calls it.
Look more closely at protected access
The word protected does not mean “subclasses only.” Desk is not a subclass of MemberCard, but it can call showWelcome because both classes are in library.
For an instance method, a subclass in another package has a further rule. An instance method is called on an object. Inside StudentCard, a call to showWelcome() works on the current student card. A call on another object whose declared type is StudentCard would also work.
However, from StudentCard in the visitors package, you cannot call showWelcome on a reference declared as a plain MemberCard. A reference is a value used to access an object. The compiler checks its declared type when applying this rule.
This rule does not stop Desk from calling showWelcome on its MemberCard parameter. Desk has access through the same-package rule.
Common access errors
When Java reports that a method is not accessible, check these points:
- Find the method declaration. Is it
private, package-private,protected, orpublic? - Compare the caller’s package with the declaring class’s package. Look at the
packageline, not just the folder names. - If the method is protected and the packages differ, check whether the caller is a subclass and whether the call follows the rule above.
- Check that the class itself is accessible. A public method in a package-private class is not generally available to code in another package.
For example, adding a call to card.resetVisits() in Main would fail to compile. Main is in visitors, while resetVisits is package-private in library. Adding a call to card.logVisit() would also fail because that method is private.
Changing every method to public may remove access errors, but it can expose steps that callers should not use directly. First decide whether the call belongs in the class’s public way of working.
Check your understanding
Exercise
Can Desk call resetVisits? Can Main call it?
Show answer
Desk can because it is in the library package. Main cannot because it is in the visitors package and resetVisits is package-private.
Exercise
Why can StudentCard call showWelcome, but not logVisit?
Show answer
showWelcome is protected, so the subclass can call it on itself. logVisit is private to MemberCard.
Exercise
What happens if you remove public from the recordVisit declaration and try to compile the example?
Show answer
recordVisit becomes package-private. The calls from StudentCard and Main are in another package, so they cannot access it. Restore public to run the example again.