09 / 12

Can you prevent a class from being inherited? How? (Sealed/Final)

Difficulty: 2/10

Preventing Inheritance with sealed/final

Yes. A class can be explicitly prevented from being inherited. Java uses the final keyword, while C# uses sealed. This is useful when a class's behavior must not be changed through inheritance, when invariants depend on the exact implementation, or when an API is intentionally closed for extension. It can also prevent consumers from creating subclasses that violate assumptions made by the class.

javascript
  1. 1

    Java: final class prevents class inheritance.

  2. 2

    C#: sealed class prevents class inheritance.

  3. 3

    Useful for preserving invariants and preventing unintended specialization.

  4. 4

    Can communicate that extension through inheritance is not part of the API contract.

  5. 5

    Sealing a class does not prevent composition or interface-based abstraction.

Follow-up Questions

  • Can a sealed/final class implement an interface?
  • Why would you seal a class for security or design reasons?
  • Can a sealed class be mocked?
  • What is the difference between sealed and private constructors?
Share

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