Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why aren't classes sealed by default?

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!

like image 224
xyz Avatar asked Oct 31 '08 00:10

xyz


People also ask

Why do we need sealed classes?

Sealed class is used to stop a class to be inherited. You cannot derive or extend any class from it. Sealed method is implemented so that no other class can overthrow it and implement its own method.

When should a class be sealed?

The main purpose of a sealed class is to take away the inheritance feature from the class users so they cannot derive a class from it. One of the best usage of sealed classes is when you have a class with static members. For example, the Pens and Brushes classes of the System.

Can sealed class be instantiated?

A sealed class is abstract by itself, it cannot be instantiated directly and can have abstract members.

What is a non sealed class?

According to this documentation, the non-sealed class allows opening part of the inheritance hierarchy to the world. It means the root sealed class permits only a closed set of subclasses to extend it.


1 Answers

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...

like image 63
Jon Skeet Avatar answered Sep 18 '22 00:09

Jon Skeet