Method Hiding

🧩 Method Hiding (in OOP)

Definition:

  • Method hiding occurs when a static method in a subclass has the same name and signature as a static method in its parent class.

  • Unlike method overriding, which involves instance methods and works with polymorphism, method hiding is resolved at compile-time because static methods are associated with the class, not the instance.

🔍 Key Points:

  • Static methods belong to the class, not the object.

  • Hiding a static method does not override the parent class's method in the same way as instance method overriding.

  • The method call is determined by the reference type (not the object type) at compile time.


Certainly! Here's the method hiding example in Python:

🐍 Method Hiding in Python

class A:
    @staticmethod
    def display():
        print("A's display")

class B(A):
    @staticmethod
    def display():
        print("B's display")

# Create an instance of class B
obj = B()
obj.display()  # Output: B's display

# Reference of type A, but object of type B
obj2 = A()
obj2.display()  # Output: A's display

🧐 Explanation:

  • Both classes A and B have a static method called display().

  • In class B, this static method hides the method in class A.

  • When you call obj.display() from an object of type B, Python calls B's method, not A's method.

🔑 Key points:

  • Method hiding occurs with static methods in Python, similar to Java.

  • The method resolution happens based on the class that defines the method (not the object type).

  • Unlike method overriding, method hiding happens at compile time, and the reference type decides which method is called.


If you want to explore more or have any other questions on this, let me know!

Updated on