Abstract classes define base classes in a hierarchy. An abstract class is an incomplete class; you can't create an instance of an abstract class. If you try, you will get a compile error. So you need to subclass an abstract class and create an instance of subclass to call an abstract class's methods.
Features
The following are the features of an abstract class:
- An abstract class cannot be instantiated.
- An abstract class may contain abstract methods and accessors.
- A non-abstract class is derived from an abstract class an must include an actual implementation of all the inherited abstract methods and accessors.
- An abstract method is implicitly a virtual method.
- Abstract method declarations are only permitted in abstract classes.
Now I will explain with an example. Here I declaed an astract class named fourwheeler containing a method explain(). And a class called maruti derived from the abstract class and I created an object of the derived class inside a main() function and call the abstract class's methods.
- namespace AbstractClasses
- {
- class Program
- {
- static void Main(string[] args)
- {
- maruti maru = new maruti();
- Console.WriteLine(maru.explain());
- Console.ReadLine();
- }
- }
- abstract class fourwheeler
- {
- public virtual string explain()
- {
-
- return "Not much is known about this four wheeler car!";
- }
- }
-
- class maruti : fourwheeler
- {
-
- }
It shows as output:
“Not much is known about this four wheeler car!”
Now if I add the explain() method to the maruti class like:
- class maruti : fourwheeler
- {
- string result = base.explain();
- result += " it is Maruti";
- return result;
- }
Then the output will be:
“Not much is known about this four wheeler car! It is maruti"If try to make an object of the abstract class then we will get an error like: