find and solve || findandsolve.com
Please wait.....

Abstract Class And Abstract Method In C#

In C#, the abstract modifier in a class declaration indicates that a class is intended only to be a base class of other classes which is declared abstract keyword. Abstraction can be achieved in two ways:

  1. Abstract class
  2. Interface

Abstract class and interface both can have abstract methods which are necessary for abstraction.


Abstract Method

A method that is declared abstract and has no body is called the abstract method. It can be declared inside the abstract class only. Its implementation must be provided by derived classes like as given below.

public abstract void draw();  

An abstract method in C# is internally a virtual method so it can be overridden by the derived class.


C# Abstract class


In the C# programming language, the abstract class is a class that is declared abstract. It can have abstract and non-abstract methods. It cannot be instantiated. Its implementation must be provided by derived classes. Here, the derived class is forced to provide the implementation of all the abstract methods.

Let's see the given example of abstract class in C# which has one abstract method draw(). Its implementation is provided by derived classes: Test and Test2. Both classes have different implementations.

using System;  

public abstract class Test
{
    public abstract void draw();
}
public class Test1: Test
{
    public override void draw()
    {
        Console.WriteLine("Test1...");
    }
}
public class Test2: Test
{
    public override void draw()
    {
        Console.WriteLine("Test2...");
    }
}
public class AbstractExample
{
    public static void Main()
    {
        Test t;
        t = new Test1();
        t.draw();
        t = new Test2();
        t.draw();
    }
}  

Output

Test1...

Test2...