Method Hiding
- Method hiding occurs when a static method in a subclass has the same signature (name and parameters) as a static method in its superclass.
- In this case, the method in the subclass hides the method in the superclass rather than overriding it, since static methods belong to the class itself, not to instances of the class.
Key Characteristics of Method Hiding:
- Applies to Static Methods: Only static methods can be hidden, while instance methods can be overridden.
- Class-Level Binding: The method to be called is determined at compile-time based on the class reference type, rather than at runtime (unlike method overriding).
- No Polymorphism: Unlike overriding, method hiding does not support polymorphism because the method called depends on the reference type, not the object type.
Example of Method Hiding:
class Parent { // Static method in parent class public static void display() { System.out.println("Static method in Parent class"); } } class Child extends Parent {
// Static method in child class (hides the parent method)
public static void display() {
System.out.println("Static method in Child class");
}
}
public class Main {
public static void main(String args) {
Parent p = new Parent();
Parent c = new Child();
// Calls the static method of Parent class
p.display(); // Output: Static method in Parent class
// Calls the static method of Parent class due to reference type
c.display(); // Output: Static method in Parent class
}
}
Explanation of Example:
- The
display()
method in theChild
class hides thedisplay()
method in theParent
class. - When the method is called using a reference of type
Parent
, the version from theParent
class is used, regardless of whether the object is an instance ofChild
.
Key Differences Between Method Hiding and Method Overriding:
\| Method Hiding \| Method Overriding \|
\|----------------------------------------------\|--------------------------------------------------\|
\| Only applicable to static methods. \| Applicable to instance methods. \|
\| The method to call is resolved at compile-time. \| The method to call is resolved at runtime (dynamic binding). \|
\| No polymorphism: The reference type determines which method is called. \| Supports polymorphism: The object type determines which method is called. \|
\| Uses the static
keyword. \| Does not require the static
keyword. \|