We know that when method declared as virtual can be implemented in child class by creating object of parent class but it is optional when we declare it as Virtual. But in some case there might be requirement that child class must and should implement particular method, in this case it should be declare as Abstract. When method is declared as abstract it is mandatory for child class to implement it, without which it can't use other members and methods of the parent class. First it must implement the abstract method in the parent class as there can be a method body not implemented for an abstract class in a parent class.
Some more points for Abstract classes
- 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 ({ })
Following the signature. For example:
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);//only method declaration
public abstract void Div(int x, int y);//only method declaration
}
}
using System;
namespace OOPSProject
{
class AbsChild : AbsParent
{
//first we have to implement abstract methods of parent class
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);//then we can invoke other methods
p.Mul(50, 30); p.Div(625, 25);
Console.ReadLine();
}
}
}