Abstract class and method in C#
The abstract classes are a special type of class. Generally, the classes which we declare will have methods with their own implementation as per their requirement that is method definition and method body. but the abstract classes will not have a method body that is no implementation.
The classes which are declared using the abstract
keyword are known as the abstract class. And methods declared using the abstract
keyword are known as abstract methods.
abstract class Demo
{
int x = 10;
abstract public void display();
}
The abstract
modifier indicates that the thing being modified has a missing or incomplete implementation.
As you can see in the above code example the class and method are declared using the abstract
keyword and the method is just declared without the body({ }
) of the method and the method declaration is ended with ;
.
Use of abstract class and methods :
- The
abstract
keyword enables you to create classes and class members that are incomplete and must be implemented in a derived class.
abstract class A
{
public abstract void display();
}
class B : A
{
public override void display()
{
Console.WriteLine("Implenented in class B");
}
}
- The purpose of an abstract class is to provide a common definition of a base class that multiple derived classes can share.
abstract class Shape
{
public abstract void GetArea();
}
class Square : Shape
{
public override void GetArea()
{
//implementation
}
}
class Triangle : Shape
{
public override void GetArea()
{
//implementation
}
}
The Shape
abstract class is implemented by the Square
and Triangle
class which override
the GetArea
method.
Note: If a class is inheriting the abstract class but not overriding the abstract method then the class needs to be declared as an
abstract
class as shown below.
abstract class A
{
public abstract void GetArea();
}
abstract class B : A
{
//Method is not implemented
//If this class is not declared abstract then it will throw a compile-time error
}
Abstract class has the following features :
An abstract class cannot be instantiated this means the object of the abstract class can't be created. We can just create a reference variable.
Abstract class can be declared without any abstract methods.
Abstract methods are meant for overridden in another class this means that abstract methods are implicitly virtual method.
Abstract methods can be declared inside only abstract classes.
Abstract class can have
static
members which can be accessed just using the class name with the.
operator.