Why can’t an object of abstract class be created?
Many developers already know that it is not possible to create an object of abstract class. However, have you ever wondered why? Why can’t an object of abstract class be created?
Let’s find out the reason together. I will first explain a bit about abstract class, if you know you can skip this section and move ahead.
What is an Abstract Class in C#?
An abstract class is a special type of class which cannot be initialized and it only acts as a base class for other classes.
Abstract classes have the following features:
- An abstract class cannot be instantiated.
- An abstract class may contain abstract methods and accessors.
- It is not possible to modify an abstract class with the sealed modifier because the two modifiers have opposite meanings. The sealed modifier prevents a class from being inherited and the abstract modifier requires a class to be inherited.
- A non-abstract class derived from an abstract class must include actual implementations of all inherited abstract methods and accessors.
Abstract class object cannot be Created – Why?
An object of abstract class cannot be created because this is how the abstract class is defined. We can create sub-types of it, but not of that type itself. The CLI will not let you do this.
An abstract class has a protected constructor (by default) allowing derived types to initialize it.
For example, the base-type Stream is abstract. Without a derived type where would the data go? What would happen when you call an abstract method? There would be no actual implementation of the method to invoke.
When to use Abstract Classes in C#?
You can refer my post – When to use Abstract Classes in C#? for knowing when to use Abstract Classes.
What does MSDN says?
MSDN: Abstract classes are closely related to interfaces. They are classes that cannot be instantiated, and are frequently either partially implemented, or not at all implemented. One key difference between abstract classes and interfaces is that a class may implement an unlimited number of interfaces, but may inherit from only one abstract (or any other kind of) class. A class that is derived from an abstract class may still implement interfaces. Abstract classes are useful when creating components because they allow you specify an invariant level of functionality in some methods, but leave the implementation of other methods until a specific implementation of that class is needed. They also version well, because if additional functionality is needed in derived classes, it can be added to the base class without breaking code.
What do you think?
If you have any questions or suggestions please feel free to email us or put your thoughts as comments below. We would love to hear from you. If you found this post or article useful then please share along with your friends and help them to learn.