Sub topic 9
What Cannot Be Overridden: static, private, and final
In earlier chapters you learned that an overriding method replaces the parent's version, and that Java picks which version to run by looking at the real object. That choice made while the program runs is called dynamic dispatch.
Not every method takes part in dynamic dispatch. Java has three keywords that stop it:
staticmethods belong to the class, not to an object.privatemethods are hidden inside their own class.finalmethods are locked, so a subclass cannot change them.
This chapter covers each one, shows what happens when you try to override it, and explains why Java works this way.
A Quick Reminder: Two Kinds of Choosing
Java can choose a method at two different times.
- Compile time is when the compiler turns your code into bytecode. A choice made here depends only on the declared type, which is the type written next to the variable name.
- Run time is when the program actually runs. A choice made here depends on the runtime type, which is the class of the real object.
Overriding works at run time. Everything in this chapter gets decided at compile time, so the runtime type has no effect on it.
Static Methods Are Hidden, Not Overridden
A static method is a method marked static. It belongs to the class itself, so you can call it without creating any object, as in Math.max(3, 4).
A static method has no object to look at, so Java cannot use the object's runtime type to choose a version. If a subclass declares a static method with the same signature, the parent's method is hidden. Hiding means the subclass now has its own separate method with the same name, and the two never replace each other.
class Parent {
static String kind() {
return "Parent.kind";
}
String who() {
return "Parent.who";
}
}
class Child extends Parent {
static String kind() {
return "Child.kind";
}
@Override
String who() {
return "Child.who";
}
}
public class Main {
public static void main(String[] args) {
Parent p = new Child();
System.out.println(p.who()); // Child.who (instance: runtime type)
System.out.println(p.kind()); // Parent.kind (static: declared type)
System.out.println(Parent.kind()); // Parent.kind
System.out.println(Child.kind()); // Child.kind
}
}Look at the two calls on p. The object is a Child, but its declared type is Parent.
p.who()is an instance method, so Java checks the object and runsChild.who.p.kind()is static, so the compiler sees onlyParent pand links the call toParent.kind. The object is never checked.
What the compiler rejects
- Putting
@OverrideonChild.kind()is a compile error: "method does not override or implement a method from a supertype." The annotation catches the mistake for you. - A static method in the child cannot use the same signature as an instance method in the parent. That is also a compile error.
- An instance method in the child cannot use the same signature as a static method in the parent. That is a compile error too.
Private Methods Are Invisible to Subclasses
A private method can be used only inside the class that declares it. A subclass cannot see it, so it has nothing to override.
If a subclass writes a method with the same name, that method is new and unrelated. The trap is that code in the parent class keeps calling its own private version.
class Greeter {
private String word() {
return "Hello";
}
String greet() {
return word() + "!";
}
}
class LoudGreeter extends Greeter {
// This is a brand-new method. It does NOT override Greeter.word().
String word() {
return "HEY";
}
}
public class Main {
public static void main(String[] args) {
Greeter g = new LoudGreeter();
System.out.println(g.greet()); // Hello!
LoudGreeter lg = new LoudGreeter();
System.out.println(lg.word()); // HEY
}
}greet() is written inside Greeter, and its call to word() points at the private Greeter.word(). The compiler fixes that link, so the object being a LoudGreeter makes no difference. The output is Hello! and not HEY!.
If you add @Override above LoudGreeter.word(), the compiler reports an error. This is a good reason to always write @Override: it tells you right away that your method does not replace anything.
Final Methods Are Locked
A final method is an instance method marked final. It is inherited like any other method, but no subclass may override it. Its body is the same for every subclass.
Use final when a method must always behave the same way, for example because other code depends on its exact steps.
class Payment {
final String receipt() {
return "Paid " + amount();
}
double amount() {
return 10.0;
}
}
class Refund extends Payment {
@Override
double amount() {
return -10.0;
}
// Uncommenting this causes a compile error:
// "receipt() in Refund cannot override receipt() in Payment;
// overridden method is final"
// String receipt() { return "Refunded"; }
}
public class Main {
public static void main(String[] args) {
Payment p = new Refund();
System.out.println(p.receipt()); // Paid -10.0
}
}This example shows a common pattern. receipt() is final, so the format of the receipt is fixed. Inside it, amount() is a normal method, so it still uses dynamic dispatch, and the Refund object supplies -10.0. You lock the overall steps and leave a few specific steps open for subclasses.
Final classes
You can also mark a whole class final. Then no class may extend it at all.
final class Money {
private final long cents;
Money(long cents) {
this.cents = cents;
}
long cents() {
return cents;
}
}
// class Coins extends Money {} // compile error: cannot inherit from final Money
public class Main {
public static void main(String[] args) {
System.out.println(new Money(250).cents()); // 250
}
}Java's own String class is final. Nobody can make a subclass of String that changes how it behaves, and that protects every program that relies on strings working correctly.
Side-by-Side Summary
| Kind of method | Can a subclass replace it? | What decides which version runs | What @Override does |
|---|---|---|---|
| Normal instance method | Yes, by overriding | Runtime type of the object | Compiles correctly |
| `static` method | No, it can only be hidden | Declared type, or the class name used | Compile error |
| `private` method | No, the subclass cannot see it | The class that contains the call | Compile error |
| `final` method | No, overriding is forbidden | There is only one version | Overriding it at all is a compile error |
Why Java Works This Way
Each rule has a simple reason:
- static: dynamic dispatch needs an object to look at. A static call has no object.
- private: a private method is an internal detail of one class. If subclasses could replace it, they could break the parent class without the parent's author knowing.
- final: the class author wants a guarantee. A final method behaves the same way in every subclass, which makes the code safer and easier to reason about.
Since none of these methods needs a runtime lookup, Java can link calls to them directly. Speed is not the reason to use them, though. Pick each keyword for what it means in your design.
Exercises
Exercise
Given class A { static String id() { return "A"; } } and class B extends A { static String id() { return "B"; } }, what does A x = new B(); System.out.println(x.id()); print, and why?
Show answer
It prints "A". id() is static, so the compiler chooses it from the declared type of x, which is A. The fact that the object is really a B does not matter. B.id() only hides A.id(); it does not override it.
Exercise
In the Greeter example, what one change to Greeter would make new LoudGreeter().greet() print "HEY!"?
Show answer
Remove the private modifier from Greeter.word() (or make it protected). Then LoudGreeter.word() truly overrides it, and the call to word() inside greet() uses dynamic dispatch, which runs LoudGreeter's version.
Exercise
A class has final void save() that calls void validate(). A subclass overrides validate(). Does the subclass's validate() run when save() is called on a subclass object? Can the subclass override save()?
Show answer
Yes, the subclass's validate() runs, because validate() is a normal instance method and uses dynamic dispatch even when called from inside a final method. No, the subclass cannot override save(). Trying to do so is a compile error because save() is final.
Exercise
You add @Override above a method in a subclass and the compiler reports "method does not override or implement a method from a supertype." Name three possible causes covered in this chapter or earlier.
Show answer
The parent method is static, so it can only be hidden. The parent method is private, so the subclass cannot see it. Or the signature does not match, for example a different parameter type or a misspelled name, so the method is a new method or an overload. (A final parent method gives a different error message: "overridden method is final".)