06 / 07

How do access modifiers affect the Overriding process? Can you make an overridden method more restrictive?

Difficulty: 3/10

Access Modifiers and Method Overriding

Access modifiers are part of the substitutability contract of an overridable method. An overriding method generally cannot reduce the visibility of the base method because code using the base type must retain the access guaranteed by that base contract. For example, a public method cannot normally be overridden as protected or private. In Java, an override can maintain or increase visibility, while C# requires the override to use compatible accessibility with the virtual/abstract base member.

javascript
  1. 1

    An override must respect the accessibility contract of the base method.

  2. 2

    Reducing visibility would break callers using the base type.

  3. 3

    Java generally permits increasing visibility when overriding.

  4. 4

    C# override accessibility must match the overridden member's accessibility constraints.

  5. 5

    Hiding a member is different from overriding it and follows different rules.

Follow-up Questions

  • Can an override increase visibility in Java?
  • Can a private method be overridden?
  • What is method hiding?
  • How does this relate to the Liskov Substitution Principle?
Share

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