Sub topic 10
Static methods are hidden, not overridden
This chapter assumes you can write a class hierarchy with extends, override an instance method with @Override, and read a method call such as animal.name(). It also assumes you know what static means for a field or method. The chapter explains why a subclass can redeclare a static method but cannot override it, and what that does to the calls you write.
Overriding and hiding are different mechanisms
When a subclass declares an instance method with the same signature as an inherited one, it overrides the method. The JVM picks the version to run at runtime, based on the actual class of the object.
When a subclass declares a static method with the same signature as an inherited static method, it hides the method. Nothing is dispatched at runtime. The compiler picks the version to call from the declared type of the expression you wrote, before the program runs.
class Animal {
static String describe() {
return "Animal";
}
String name() {
return "Animal";
}
}
class Dog extends Animal {
static String describe() {
return "Dog";
}
@Override
String name() {
return "Dog";
}
}
public class HidingDemo {
public static void main(String[] args) {
Animal a = new Dog();
System.out.println(a.name());
System.out.println(a.describe());
}
}This prints Dog and then Animal. The variable a has declared type Animal and runtime type Dog. name() is an instance method, so the runtime type decides and you get Dog. describe() is static, so the declared type decides and you get Animal. The object a refers to plays no part in that second call.
Every static call is bound at compile time
A static method belongs to a class, not to an object, so there is no object whose type could be consulted. The compiler works out the target method and writes it into the bytecode. That has several visible consequences.
class Vehicle {
static String kind() {
return "Vehicle";
}
}
class Truck extends Vehicle {
static String kind() {
return "Truck";
}
}
public class BindingDemo {
public static void main(String[] args) {
Vehicle v = new Truck();
Truck t = new Truck();
Vehicle none = null;
System.out.println(v.kind());
System.out.println(t.kind());
System.out.println(Vehicle.kind());
System.out.println(Truck.kind());
System.out.println(none.kind());
}
}The output is Vehicle, Truck, Vehicle, Truck, Vehicle.
The last line shows the most surprising result. Calling a static method through a null reference does not throw a NullPointerException. The compiler uses only the declared type Vehicle and never touches the reference. Most compilers and IDEs warn about calling a static method through an instance expression. Treat that warning as a real defect signal, because the code suggests dynamic dispatch that does not happen.
A hidden method is still called by name from inherited code
Hiding also affects code inside the superclass. An unqualified call to a static method inside a class always refers to that class's own version, even when the instance is a subclass.
class Base {
static String kind() {
return "Base";
}
String showStatic() {
return kind();
}
String who() {
return "Base";
}
String showInstance() {
return who();
}
}
class Child extends Base {
static String kind() {
return "Child";
}
@Override
String who() {
return "Child";
}
}
public class InsideDemo {
public static void main(String[] args) {
Base b = new Child();
System.out.println(b.showStatic());
System.out.println(b.showInstance());
}
}This prints Base and then Child. Inside showStatic(), the call kind() was bound to Base.kind() when Base was compiled. Inside showInstance(), the call who() is a virtual call, so the real Child object supplies the answer.
If you need a template-method style design, where shared code calls a step that subclasses customize, the step must be an instance method. A static step cannot be customized from a subclass.
What the compiler allows and rejects
The language has strict rules for a subclass method with the same signature as an inherited one. The pairing of static and instance matters.
| Superclass method | Subclass method | Result |
|---|---|---|
| instance | instance | Overrides. Runtime dispatch. |
| static | static | Hides. Compile-time binding. |
| static | instance | Compile error: the overridden method is static. |
| instance | static | Compile error: the overriding method is static. |
A mixed pair never compiles. You cannot accidentally turn one kind into the other by redeclaring a method.
class Parent {
static void a() {
}
void b() {
}
}
class Broken extends Parent {
// void a() { } // error: overridden method is static
// static void b() { } // error: overriding method is static
}Both commented-out lines fail to compile. Remove the comment markers to see the error messages.
Two more rules follow from the fact that hiding is not overriding in the strict sense, though the compiler still checks similar constraints:
- A hiding method cannot have weaker access than the hidden one. If
Parent.a()ispublic,Broken.a()cannot be package-private. - The return type must be compatible, and a hiding method cannot declare checked exceptions that the hidden method does not allow.
Because hiding is not overriding, @Override on a static method is always an error. The annotation asks the compiler to confirm that the method overrides something, and a static method never does. This is a useful safety net. If you meant to override and typed static by mistake, the annotation reports it immediately.
class Cat extends Animal {
// @Override // error: static methods cannot be annotated with @Override
static String describe() {
return "Cat";
}
}Static fields are hidden too
Fields are never dispatched at runtime, for static and instance fields alike. A subclass field with the same name hides the inherited one, and the declared type of the expression selects the field.
class Source {
static String label = "source";
}
class Derived extends Source {
static String label = "derived";
}
public class FieldHidingDemo {
public static void main(String[] args) {
Source s = new Derived();
System.out.println(s.label);
System.out.println(((Derived) s).label);
System.out.println(Source.label);
System.out.println(Derived.label);
}
}The output is source, derived, source, derived. A cast changes the declared type of the expression, so it changes which field the compiler picks. Hiding a field is almost always a mistake in design. Pick a different name instead.
Reaching the hidden version
You can still call the hidden method explicitly. Qualify the call with the superclass name:
class Puppy extends Animal {
static String describe() {
return "Puppy of " + Animal.describe();
}
}super.describe() also compiles in an instance context, but it reads as if it were a virtual call, so Animal.describe() is clearer.
Static methods in interfaces
A static method declared in an interface is not inherited by implementing classes or by sub-interfaces. You must call it through the interface name. This avoids the hiding problem entirely, because there is no inherited method to hide.
interface Greeter {
static String hello() {
return "hello";
}
}
class Polite implements Greeter {
}
public class InterfaceStaticDemo {
public static void main(String[] args) {
System.out.println(Greeter.hello());
// System.out.println(Polite.hello()); // compile error
}
}Decision criteria and common errors
Use hiding rarely. These guidelines cover most cases:
- If the behavior should vary by object type, make it an instance method and override it. Do not rely on static methods with the same name.
- If a subclass needs its own version of a helper, give the helper a different name so readers do not wonder which one runs.
- Call static members through the class name, never through a variable.
- Add
@Overrideto every method you intend to override. The compiler then catches the case where you wrotestaticby accident. - Do not hide fields. Different names are cheaper than the confusion.
Common errors:
- Expecting polymorphism from static methods. A factory such as
Animal.create()in a hierarchy does not becomeDog.create()because the caller holds aDog. Only the written class name counts. - Believing a
nullcall must fail.none.kind()succeeds because the reference is never evaluated for dispatch. - Testing with mocks. Mocking frameworks that rely on subclassing or proxies cannot replace a static method, since it is not dispatched through the object. This is one reason static helpers make code harder to test.
Exercise
Given class A { static String f() { return "A"; } String g() { return f(); } } and class B extends A { static String f() { return "B"; } }, what does new B().g() return, and why? What would change if f were a non-static method that B overrides?
Show answer
It returns "A". The call f() inside g() is a static call, so the compiler bound it to A.f() when A was compiled, and the runtime type B has no effect. If f were an instance method overridden in B, the call would be virtual, the real object is a B, and g() would return "B".
Exercise
What does this program print, and does the last line throw an exception? Animal a = new Dog(); Animal n = null; System.out.println(a.describe()); System.out.println(n.describe()); Use the Animal and Dog classes from the first example.
Show answer
It prints "Animal" twice and throws nothing. Static calls are bound from the declared type Animal at compile time. The reference value is never used, so the null reference causes no NullPointerException.