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条回答
SAY GOODBYE
2楼-- · 2019-01-14 15:30

I'd say it was just a mistake. I know many people (including myself) who believe that classes should indeed be sealed by default. There are at least a couple of people in the C# design team in that camp. The pendulum has swung somewhat away from inheritance since C# was first designed. (It has its place, of course, but I find myself using it relatively rarely.)

For what it's worth, that's not the only mistake along the lines of being too close to Java: personally I'd rather Equals and GetHashCode weren't in object, and that you needed specific Monitor instances for locking too...

查看更多
SAY GOODBYE
3楼-- · 2019-01-14 15:30

You could probably make just as many arguments in favor of sealed-by-default as you could against it. If it were the other way around, someone would be posting the opposite question.

查看更多
干净又极端
4楼-- · 2019-01-14 15:35

I can't recall having heard a rationale for the decision to have classes not sealed by default. However, there are certainly quite a few people who believe that C# should have been spec'ed to have sealed be the default:

http://codebetter.com/blogs/patricksmacchia/archive/2008/01/05/rambling-on-the-sealed-keyword.aspx

查看更多
你好瞎i
5楼-- · 2019-01-14 15:42

sealed classes prevent inheritance and therefore are an OO abombination. see this rant for details ;-)

查看更多
叼着烟拽天下
6楼-- · 2019-01-14 15:44

I see two simple reasons:

  1. Inheritance is a foundational principle of OO, so disallowing it by default wouldn't be intuitive.
  2. The majority of classes are designed to allow inheritance, so allowing inheritance by default saves typing.
查看更多
Juvenile、少年°
7楼-- · 2019-01-14 15:44

80% of the features of Word go unused. 80% of classes don't get inherited from. In both cases, once in a while, someone comes along and wants to use or reuse a feature. Why should the original designer prohibit reuse? Let the reuser decide what they want to reuse.

查看更多
登录 后发表回答