Abstract class in C# is declared using keyword "abstract". Now, what does abstract class does?, if the class is created for the purpose of providing common fields and members to all sub-classes (wihch will inherit it) then this type of class is called an abstract class. It is used when we don't want to create the object of base-class.
Abstract class can contain, both, non-abstract or abstract methods.
The abstract keyword allows us to create classes and class members which are incomplete and should be implemented in a derived class.
Syntax for creating Abstract class
<access_specifier> abstract class Class_Name
{
}
Example:
using System;
namespace AbstractClassExample
{
//Creating an Abstract Class
public abstract class BaseClass
{
//Non abstract method
public int addition(int a, int b)
{
return a + b;
}
//An abstract method, overridden in derived class
public abstract int multiplication(int a, int b);
}
//child class, derived from BaseClass
public class DerivedClass:BaseClass
{
public static void Main(string[] args)
{
DerivedClass cal = new DerivedClass();
int added = cal.addition(10,20);
int multiplied = cal.multiplication(10,2);
Console.WriteLine("Addition result: {0}", added);
Console.WriteLine( "Multiplication result: {0}",multiplied);
}
public override int multiplication(int a, int b)
{
return a * b;
}
}
}
output:
Addition result: 30
Multiplication result: 20
As you can see in the above example, we have created Asbtract class named as BaseClass
, which is used in derived class. Abstract class also has two methods, one of which is non-abstract method, which we can use directly in derived class, no need to provide it's definition in derived class.
While the other method which is marked as asbtract
in base class needs to be defined in derived class.
As we have discussed above, an abstract class is a partially defined class that cannot be instantiated. It includes some implementation, but commonly functions as pure virtual- declared only by their signature.
So, the purpose of an abstract class is to define some common behavior that can be inherited by multiple subclasses, without implementing the entire class. In other words, we should use abstract class to define common behaviour of sub-classes.