Java ProgramsOOPMethod Hiding

Method Hiding in Java

intermediate·  OOP  ·  Inheritance

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.

Input
Vehicle v = new Car(); v.category();
Output
Vehicle category Car category

Java Program

Java
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

Vehicle category Car category

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.

How It Works
  1. 1Vehicle and Car each declare their own static void category() with the identical signature.
  2. 2Vehicle v = new Car(); creates an actual Car object, but stores it in a variable declared as type Vehicle.
  3. 3v.category() looks purely at v's declared type, Vehicle, to decide which category() to call — the fact that the real object is a Car never enters into it.
  4. 4Car.category(), called directly on the class, unambiguously runs Car's own version.
Even though 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.

Key Concepts

static methodmethod hidingcompile-time resolution

Related Programs