What do you mean by word “Abstract”?
Abstract means (as a noun) summary not a whole story.
"Take vehicle and car, vehicle is an abstract of car."
So in an abstract class we have abstract and non-abstract methods. In the class abstract methods don’t have implementation; we can implement those later in derived classes.
We can create an abstract class through using the abstract keyword. We cannot have an instance of abstract class.
If we try to make an instance of abstract class we get an compile time error "cannot create an instance of abstract class or interface".
So why we need abstract classes? We can have abstract classes just for inheritance. It provides a common pattern to all the derived classes.
Some basic facts about abstract class:
- It is mandatory to override all abstract method in the derived class.
- Abstract classes are only for inheritance.
- An abstract class can also contain methods with complete implementation, besides abstract methods.
- Abstract classes have effect only when used with inheritance.
- An abstract member is not implemented in the base class and must be implemented in derived classes.
- A member defined as virtual must be implemented in the base class, but may be optionally overridden in the derived class if different behavior is required.
- An abstract class cannot support multiple inheritances.
- Abstract methods cannot have body.
Here is an example code of abstract class and it's output.
- using System;
- namespace ConsoleApplication1
- {
- abstract class AbsClass
- {
-
- public abstract int MultiplyTwoNumbers(int x, int y);
- public abstract int SubtractTwoNumbers(int p, int q);
-
- public int AddThreeNumbers(int a, int b, int c)
- {
- return a + b + c;
- }
- }
- class DerivedClass : AbsClass
- {
-
- public override int MultiplyTwoNumbers(int x, int y)
- {
- return x * y;
- }
- public override int SubtractTwoNumbers(int p, int q)
- {
- return p - q;
- }
- }
- class Program
- {
- static void Main()
- {
- DerivedClass obj = new DerivedClass();
-
- int Addition = obj.AddThreeNumbers(10, 20, 50);
- int Multipication = obj.MultiplyTwoNumbers(3, 50);
- int Substraction = obj.SubtractTwoNumbers(10, 3);
-
- Console.Write("Addition of 10, 20 and 50 = " + Addition.ToString() + "\n" + "Mutiplication of 3 and 50 = " + Multipication.ToString() + "\n" + "Subtraction of 10 and 3 = " + Substraction.ToString());
- Console.ReadLine();
- }
- }
- }
Output