Why seal a class?

前端 未结 10 1938
醉酒成梦
醉酒成梦 2020-11-28 04:51

I\'d like to hear what is the motivation behind the bulk of sealed classes in the .Net framework. What is the benefit of sealing a class? I cannot fathom how not allowing in

10条回答
  •  一个人的身影
    2020-11-28 05:33

    Classes should either be designed for inheritance or prohibit it. There is a cost to designing for inheritance:

    • It can pin down your implementation (you have to declare which methods are going to call which other methods, in case a user overrides one but not the other)
    • It reveals your implementation rather than just the effects
    • It means you have to think of more possibilities when designing
    • Things like Equals are hard to design in an inheritance tree
    • It requires more documentation
    • An immutable type which is subclassed may become mutable (ick)

    Item 17 of Effective Java goes into more details on this - regardless of the fact that it's written in the context of Java, the advice applies to .NET as well.

    Personally I wish classes were sealed by default in .NET.

提交回复
热议问题