Method Hiding in Java
Problem
Method hiding happens when a subclass declares a static method with the same signature as a static method in its parent — unlike overriding an instance method, which version runs is decided by the reference's declared type, not the object's actual class.
Create a Vehicle class and a Car subclass, each with a static category method, and confirm which version runs when called through a Vehicle-typed reference.
Java Program
class Vehicle {
static void category() {
System.out.println("Vehicle category");
}
}
class Car extends Vehicle {
static void category() {
System.out.println("Car category");
}
}
public class MethodHidingDemo {
public static void main(String[] args) {
Vehicle v = new Car();
v.category(); // resolved by v's declared type (Vehicle), not the actual object's class
Car.category();
}
}Output
Core Logic
Because static methods belong to the class itself rather than to any particular object, Java resolves which one to call using the reference's declared type, decided at compile time — not the object's real class, decided at runtime.
- 1
VehicleandCareach declare their ownstatic void category()with the identical signature. - 2
Vehicle v = new Car();creates an actualCarobject, but stores it in a variable declared as typeVehicle. - 3
v.category()looks purely atv's declared type,Vehicle, to decide whichcategory()to call — the fact that the real object is aCarnever enters into it. - 4
Car.category(), called directly on the class, unambiguously runsCar's own version.
v holds a real Car object, v.category() prints "Vehicle category" — the exact opposite of what overriding an instance method would produce.Key Point: This is the key difference from overriding: an overridden instance method is chosen by the object's actual runtime type, but a hidden static method is chosen by the reference's declared type at compile time — Car's version doesn't hide Vehicle's so much as exist as a separate method that happens to share its name.