What's the difference between an abstract class and a static one?

后端 未结 9 1878
臣服心动
臣服心动 2020-12-02 18:55

Neither is instantiable. What are the differences, and in what situations might you use one or the other?

相关标签:
9条回答
  • 2020-12-02 19:18

    static indicates the class can only have static members and you cannot create an instance of it. This is used for stateless functionality (for example a type that just defines extension methods, or utility methods). You can also declare a member static on a non-static class. This allows you to attach functionality to a type without having to instantiate it.

    Here's more detail on using static members and classes.

    abstracts define the basic structure and functionality shared by all derivative types, but cannot be used by themselves. Think of them as, I suppose, a blue print and a contract. This is a core concept for OOP.

    Here's more detail on using abstracts.

    0 讨论(0)
  • 2020-12-02 19:20

    An abstract class is intended to be used as a base of a class inheritance hierarchy. A static class cannot be the base of a class inheritance hierarchy.

    A static class is intended for singleton state or stateless functionality. An abstract class is not suitable for singleton functionality, because, even though it may contain static methods and fields as a static class does, it cannot forbid inheritance, so the singleton use may be defeated by subclasses. Or, at the very least, it would be confusing to other programmers, because its definition would communicate an intent that is different from its actual intended use.

    The superficial similarity between abstract and static classes is only in the fact that neither may be instantiated. Beyond that, they are completely different animals with completely different use cases.

    0 讨论(0)
  • 2020-12-02 19:26

    Abstract Class (Base class): Enables other classes to inherit from this class (one class acquires the properties (methods and fields) of another) , but forbids to instantiate i.e we cannot have objects of this class. http://csharp.net-tutorials.com/classes/abstract-classes

    Static Class: This class cannot be instantiated. Also this class cannot be inherited. To access methods of this class, you can directly use classname.method. https://social.technet.microsoft.com/wiki/contents/articles/21028.difference-between-static-class-sealed-class-and-abstract-class-in-c.aspx

    0 讨论(0)
提交回复
热议问题