12 / 12

What is the difference between 'Overriding' and 'Hiding/Method Shadowing'?

Difficulty: 3/10

Overriding vs Method Hiding

Overriding replaces or specializes a virtual method implementation and participates in runtime polymorphism. Method hiding, or shadowing, defines a separate member with the same or related name in the derived class; the member selected can depend on the compile-time type of the reference. This distinction is important because hiding can produce surprising behavior when an object is accessed through a base-type reference. As a senior engineer, I prefer explicit overriding for polymorphic behavior and use hiding only when the semantics are intentional.

javascript
  1. 1

    Overriding is runtime polymorphism.

  2. 2

    The actual object's implementation is selected for an overridden virtual method.

  3. 3

    Hiding creates a distinct member in the derived class.

  4. 4

    With hiding, the compile-time/reference type can affect which method is selected.

  5. 5

    Hiding can make APIs confusing, so it should be explicit and intentional.

  6. 6

    The exact mechanics differ between Java and C#.

Follow-up Questions

  • What is runtime polymorphism?
  • How does method hiding work in C#?
  • Does Java support method hiding?
  • What happens when an overridden method is called through a base reference?
  • When would intentional method hiding be appropriate?
Share

Share via WhatsApp, X, Facebook, LinkedIn or copy link. Open Graph preview enabled.