Method hiding is a concept that occurs when a static method in a subclass has the same signature as a static method in its superclass. This is different from method overriding, which deals with instance methods and runtime polymorphism.
In method hiding, the version of the static method that gets executed is determined by the type of the reference, not the object that it points to.
Method hiding is applicable only to static methods. The static method in the subclass must have the same signature (name and parameters) as the static method in the superclass.
The method that gets executed depends on the reference type, not the actual object type.
Unlike instance methods, static methods do not support polymorphism because they are resolved at compile-time, not runtime.
class Parent {
static void display() {
System.out.println("Static method in Parent class");
}
void show() {
System.out.println("Instance method in Parent class");
}
}
class Child extends Parent {
static void display() {
System.out.println("Static method in Child class");
}
@Override
void show() {
System.out.println("Instance method in Child class");
}
}
public class MethodHidingExample {
public static void main(String[] args) {
Parent parentRef1 = new Parent();
Parent parentRef2 = new Child();
Child childRef = new Child();
// Static method calls
Parent.display(); // Output: Static method in Parent class
Child.display(); // Output: Static method in Child class
parentRef2.display(); // Output: Static method in Parent class
// Instance method calls
parentRef1.show(); // Output: Instance method in Parent class
parentRef2.show(); // Output: Instance method in Child class
childRef.show(); // Output: Instance method in Child class
}
}
Difference with Method Overriding
Method Overriding only applies to instance methods. Here method to be executed is determined by the object type (runtime polymorphism). It supports polymorphism.