Sub topic 9
Access Rules for Overridden Methods
A subclass is a class built from another class, called its superclass. The subclass can replace the behavior of an inherited method. This is called overriding.
For example, a Message class might have a title() method. An Alert subclass can override title() to return a more specific title.
Java places a limit on an override: it cannot make the inherited method less accessible. This chapter explains that rule, why it matters, and how to check your code.
You should already know how to declare Java classes, methods, and constructors. You should also know that public, protected, package-private, and private control where code can access a member.
Why an override cannot restrict access
A caller is code that uses a method. If a superclass offers a public method, callers can use that method on objects described by the superclass type.
A superclass reference is a variable whose declared type is the superclass. It can refer to an object of a subclass. For example, a variable of type Message can refer to an Alert object.
When a caller uses a public method through that reference, Java can run the subclass’s override. The subclass must not remove the access that the superclass promised. If Message.title() is public, Alert.title() must also be public.
This rule lets callers use the superclass API without having to check which subclass object they received.
The diagram applies to an accessible instance method that Alert overrides. An instance method is a method called on an object.
The access rule
For an inherited instance method that can be overridden, the subclass must use the same access level or a wider one.
| Access in the superclass | Allowed access in the override | Not allowed |
|---|---|---|
| public | public | protected, package-private, private |
| protected | protected or public | package-private, private |
| package-private | package-private, protected, or public | private |
Package-private means that the declaration has no access word. The last row applies when the subclass can inherit and override that method, such as when both classes are in the same package.
A package is a way to group Java classes. A package-private method is generally available only inside its package. If a direct subclass is in a different package, it does not inherit the superclass’s package-private method. A same-named method in that subclass is not an override of it.
The table does not include private superclass methods. Those methods cannot be overridden, even if a subclass declares a method with the same name.
A worked example
This example shows three valid overrides:
- A public method stays public.
- A protected method becomes public.
- A package-private method becomes protected.
It also shows two private methods with the same name. They are separate methods, not an override.
You need a Java Development Kit installed to run the example. The commands below use a Bash shell. Create the folders first:
mkdir -p src/notices src/app outSave the following file as src/notices/Message.java:
package notices;
public class Message {
public String title() {
return "Message";
}
protected String format() {
return "Message format";
}
String category() {
return "General";
}
private String secret() {
return "Message secret";
}
public String reveal() {
return secret();
}
public String showFormat() {
return format();
}
}Save this file as src/notices/Alert.java:
package notices;
public class Alert extends Message {
@Override
public String title() {
return "Alert";
}
@Override
public String format() {
return "Alert format";
}
@Override
protected String category() {
return "Warning";
}
private String secret() {
return "Alert secret";
}
public String revealAlertSecret() {
return secret();
}
}Save the following file as src/app/Main.java:
package app;
import notices.Alert;
import notices.Message;
public class Main {
public static void main(String[] args) {
Alert alert = new Alert();
Message message = alert;
System.out.println(message.title());
System.out.println(message.showFormat());
System.out.println(alert.format());
System.out.println(message.reveal());
System.out.println(alert.revealAlertSecret());
}
}Compile and run the three files from the folder that contains src:
javac -d out src/notices/Message.java src/notices/Alert.java src/app/Main.java
java -cp out app.MainThe program prints these five lines, in order:
- Alert
- Alert format
- Alert format
- Message secret
- Alert secret
Follow the overrides
The variables alert and message refer to the same Alert object. Their declared types differ: alert is declared as Alert, while message is declared as Message.
The call to message.title() is allowed because title() is public in Message. The object is an Alert, so Java runs Alert.title(). That is why the first line is Alert.
The call to message.showFormat() runs the inherited showFormat() method from Message. Inside that method, the call to format() runs Alert.format(), because the object is an Alert and format() is overridden. That produces the second line.
The call to alert.format() is also allowed. Alert made its override public, so the app.Main class can call it through an Alert reference. That produces the third line.
The category() override is valid too. Message and Alert are in the same package, so Alert can override Message’s package-private category() method. Alert widens its access to protected.
Follow the private methods
Message.secret() is private. Alert.secret() has the same name and parameters, but it does not override Message.secret(). It is a separate method.
The inherited reveal() method belongs to Message and calls Message.secret(). That is why the fourth line is Message secret.
Alert.revealAlertSecret() calls Alert.secret(). That is why the fifth line is Alert secret.
Do not put @Override above Alert.secret(). Java would reject it because that method does not override a superclass method.
The declared type still matters
Widening an override does not change the declaration in the superclass.
In the example, format() is protected in Message but public in Alert. The two variables refer to the same object, yet their declared types give the caller different access:
| Call from app.Main | Result |
|---|---|
| alert.format() | Allowed: Alert declares format() as public. |
| message.format() | Not allowed: Message declares format() as protected, and app.Main is not in the notices package or a Message subclass. |
| message.showFormat() | Allowed: showFormat() is public in Message. It then calls format() from inside Message. |
Java checks whether the call is allowed using the declared type of the reference. For an allowed call to an overridden instance method, the object’s actual class then determines which implementation runs. An implementation is the code inside a method.
You can test this rule. Add a call to message.format() inside Main.main(), then compile again. The compiler, the tool that checks and translates Java source code, reports an access error. Remove the call before continuing.
Use @Override to catch mistakes
The @Override annotation tells the compiler that a method is intended to override an inherited method. An annotation is a marker that gives the compiler or other tools information about code.
The annotation does not make a method override another method. Java’s rules determine that. Instead, @Override asks the compiler to report an error if no suitable method is being overridden.
It can catch mistakes such as:
- A misspelled method name.
- Different parameter types.
- An attempt to override a private method.
- An attempt to override a package-private method that the subclass does not inherit.
Parameters are the inputs listed in a method declaration. For example, format() and format(String value) have different parameters. Declaring the second method does not override the first.
Use @Override on every method you intend to override. It makes the intent clear and helps catch errors when code changes.
Common access errors
Making an override too narrow
Suppose you change Alert.title() from public to protected. Compilation fails because Message.title() is public. The fix is to keep Alert.title() public.
Similarly, removing protected from an override of a protected method makes the override package-private. That is narrower, so Java rejects it. Add protected back, or make the method public if wider access is part of the design.
A private method is not a valid way to hide an inherited public, protected, or accessible package-private method with the same signature. A signature is the method name and its parameter types. Java reports an error because the new declaration would reduce access.
Expecting a different-package method to override
Imagine that Message has its package-private category() method, but a direct subclass is declared in a different package. That subclass does not inherit Message.category().
If the subclass declares its own category() method, the two methods are separate. Adding @Override to the subclass method causes an error. If overriding is intended across packages, the superclass author can make the original method protected or public, if that access is appropriate.
Forgetting interface method access
An interface is a Java type that describes operations a class can provide. An ordinary instance method declared in an interface is public, even if the declaration does not write public.
When a class implements such a method, its implementation must be public. Leaving out the access word makes the method package-private, which is too narrow.
Expecting every same-named method to override
Access is not the only condition for overriding. A method marked final cannot be overridden. A final method is one whose declaration prevents subclasses from replacing it.
A static method belongs to a class rather than to an individual object. A same-named static method in a subclass can hide an inherited static method; it does not override it. Constructors are not methods and cannot be overridden.
Choose access with care
Keeping the same access level is often the simplest choice. Widen access when callers need the subclass method as part of the subclass’s API, not merely because Java permits it.
For example, making Alert.format() public lets callers use it directly through an Alert reference. That also makes it a public part of Alert’s design. Changing or removing it later could affect callers.
Access checks do not guarantee that an override behaves sensibly. An override should still respect what callers reasonably expect from the superclass method. If a public method promises a readable title, an override that returns an unrelated value may compile but still surprise callers.
Practice
Exercise
A superclass declares a public instance method. Can an override be protected?
Show answer
No. The override must be public because protected is narrower than public.
Exercise
A superclass and subclass are in the same package. The superclass method is package-private. Can the override be protected?
Show answer
Yes. Protected is wider than package-private for this rule.
Exercise
In the worked example, why can app.Main call alert.format() but not message.format()?
Show answer
Alert declares format() as public. Message declares it as protected, and app.Main cannot access that protected declaration through the Message reference.
Exercise
A superclass has a private method named secret(). Its subclass declares a private method with the same name and parameters. Is the subclass method an override?
Show answer
No. The superclass method is private and cannot be overridden. The subclass method is separate.
Exercise
A class implements an ordinary interface method but leaves out the access word. Why can compilation fail?
Show answer
The interface method is public. The implementation is package-private without an access word, so it is too narrow. Declare it public.