We know that when a method is declared as virtual, it can be implemented in a child class but it is optional. But what if there is requirement that child class must implement a method. To achieve this, we can declare method as an abstract method. When a method is declared as an abstract method, it is mandatory for all derived classes to implement it. Otherwise, the compiler will throw an error. Uually the parent class has a body and signature of the method without any implementation. The derived or child class has the actual implementation of the method.
Some important points about abstract methods:
- An abstract method is implicitly a virtual method.
- Abstract method declarations are only permitted in abstract classes.
- Because an abstract method declaration provides no actual implementation, there is no method body; the method declaration simply ends with a semicolon and there are no braces ({ })
Here is an example of implementation of an abstract method.
- using System;
- namespace OOPSProject
- {
- abstract class AbsParent
- {
- public void Add(int x, int y)
- {
- Console.WriteLine(x + y);
- }
- public void Sub(int x, int y)
- {
- Console.WriteLine(x - y);
- }
- public abstract void Mul(int x, int y);
- public abstract void Div(int x, int y);
- }
- }
- using System;
- namespace OOPSProject
- {
- class AbsChild : AbsParent
- {
-
- public override void Mul(int x, int y)
- {
- Console.WriteLine(x * y);
- }
- public override void Div(int x, int y)
- {
- Console.WriteLine(x / y);
- }
- static void Main()
- {
- AbsChild c = new AbsChild();
- AbsParent p = c;
- p.Add(100, 50); p.Sub(156, 78);
- p.Mul(50, 30); p.Div(625, 25);
- Console.ReadLine();
- }
- }
- }