Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can an abstract class not be sealed or static?

Why can an abstract class not be sealed or static?

And I am also confused about the question Why declare static classes as sealed and abstract in C#?.

like image 587
anomepani Avatar asked Jan 07 '14 06:01

anomepani


1 Answers

  1. static class cannot be marked sealed because it is made sealed by compiler by default.

    Static classes are sealed and therefore cannot be inherited.

  2. static class cannot be marked as abstract, because it would be pointless. abstract class makes sense when you want all derived classes to implement same part of the logic. But because static class cannot be derived there is no way other class will implement these gaps.

    They cannot inherit from any class except Object.

Both quotes from Static Classes and Static Class Members (C# Programming Guide).

C# specification is a little more detailed about that:

10.1.1.3 Static classes

A static class may not include a sealed or abstract modifier. Note, however, that since a static class cannot be instantiated or derived from, it behaves as if it was both sealed and abstract.

You can read what does it mean for class to be sealed or abstract:

An abstract class cannot be instantiated directly, and it is a compile-time error to use the new operator on an abstract class

The sealed modifier is used to prevent derivation from a class. A compile-time error occurs if a sealed class is specified as the base class of another class.

Update

And a word about an article linked in the query you mentioned (Static Class Design). It's already stated in accepted answer from that question. If you read carefully you can see that:

DO declare static classes as sealed, abstract, and add a private instance constructor if your programming language does not have built-in support for static classes.

.NET (so C# as well) do have built-in support for static classes, so you don't have (and even can't) to make your classes pseudo-static by marking it both sealed and abstract.

like image 73
MarcinJuraszek Avatar answered Sep 22 '22 12:09

MarcinJuraszek