Why aren't classes sealed by default?

2019-01-14 14:51发布

I was just wondering, since the sealed keyword's existence indicates that it's the class author's decision as to whether other classes are allowed to inherit from it, why aren't classes sealed by default, with some keyword to mark them explicitly as extensible?

I know it's somewhat different, but access modifiers work this way. With the default being restrictive and fuller access only being granted with the insertion of a keyword.

There's a large chance that I haven't thought this through properly, though, so please be humane!

9条回答
在下西门庆
2楼-- · 2019-01-14 15:51

In my opinion there should be no default syntax, that way you always write explicitly what you want. This forces the coder to understand/think more.

If you want a class to be inheritable then you write

public extensible class MyClass

otherwise

public sealed class MyClass

BTW I think the same should go with access modifiers, disallow default access modifiers.

查看更多
太酷不给撩
3楼-- · 2019-01-14 15:56

Merely deriving from an unsealed class doesn't change the class's behavior. The worst that can happen is that a new version of the base class will add a member with the same name as the deriving class (in which case there will just be a compiler warning saying you should use the new or override modifier) or the base class is sealed (which is a design no-no if the class has already been released into the wild). Arbitrary sublassing still complies with the Liskov Substitution Principle.

The reason that members are not overridable by default in C# is that because overriding a method can change the base class's behaviour in a way that the base class's author didn't anticipate. By making it explicitly abstract or virtual, it's saying that the author is aware that that it can change or is otherwise beyond their control and the author should have taken this into account.

查看更多
Lonely孤独者°
4楼-- · 2019-01-14 15:57

For the same reason why objects are not private by default

or

to be consistent with the object analogue, which is objects are not private by default

Just guessing, coz at the end of the day it's a language's design decision and what the creators say is the canon material.

查看更多
登录 后发表回答