Open In App

C# | Abstract Classes

Last Updated : 10 Apr, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

In C#, an abstract class is a class that cannot be instantiated. Instead, it serves as a base class for other classes to inherit from. Abstract classes are used to define a common set of behaviors or properties that derived classes should have.

To create an abstract class in C#, you use the “abstract” keyword before the class definition. Here is an example:

C#




using System;
 
public abstract class Animal
{
    public abstract string Sound { get; }
 
    public virtual void Move()
    {
        Console.WriteLine("Moving...");
    }
}
 
public class Cat : Animal
{
    public override string Sound => "Meow";
 
    public override void Move()
    {
        Console.WriteLine("Walking like a cat...");
    }
}
 
public class Dog : Animal
{
    public override string Sound => "Woof";
 
    public override void Move()
    {
        Console.WriteLine("Running like a dog...");
    }
}
 
class Program
{
    static void Main(string[] args)
    {
        Animal[] animals = new Animal[] { new Cat(), new Dog() };
 
        foreach (Animal animal in animals)
        {
            Console.WriteLine($"The {animal.GetType().Name} goes {animal.Sound}");
            animal.Move();
        }
    }
}


Output

The Cat goes Meow
Walking like a cat...
The Dog goes Woof
Running like a dog...

Abstraction in C# is the process to hide the internal details and show only the functionality. The abstract modifier indicates the incomplete implementation. The keyword abstract is used before the class or method to declare the class or method as abstract. Also, the abstract modifier can be used with indexers, events, and properties

Example: 

public abstract void geek();
// this indicates the method 'geek()' is abstract
 
abstract class gfg
// this indicates the class 'gfg' is abstract

Abstract Method: A method that is declared abstract, has no “body” and is declared inside the abstract class only. An abstract method must be implemented in all non-abstract classes using the override keyword. After overriding, the abstract method is in the non-Abstract class. We can derive this class in another class, and again we can override the same abstract method with it.

Syntax: 

public abstract void geek();
// the method 'geek()' is abstract

Abstract Class: This is the way to achieve the abstraction in C#. An Abstract class is never intended to be instantiated directly. An abstract class can also be created without any abstract methods, We can mark a class abstract even if doesn’t have any abstract method. The Abstract classes are typically used to define a base class in the class hierarchy. Or in other words, an abstract class is an incomplete class or a special class we can’t be instantiated. The purpose of an abstract class is to provide a blueprint for derived classes and set some rules that the derived classes must implement when they inherit an abstract class. We can use an abstract class as a base class and all derived classes must implement abstract definitions. 

Syntax:  

abstract class gfg{}
// class 'gfg' is abstract

Important Points: 

  • Generally, we use abstract class at the time of inheritance.
  • A user must use the override keyword before the method is declared as abstract in the child class, the abstract class is used to inherit in the child class.
  • An abstract class cannot be inherited by structures.
  • It can contain constructors or destructors.
  • It can implement functions with non-Abstract methods.
  • It cannot support multiple inheritances.
  • It can’t be static.

Example 1: Program to show the working of an abstract class

C#




// C# program to show the
// working of abstract class
using System;
 
// abstract class 'GeeksForGeeks'
public abstract class GeeksForGeeks {
 
    // abstract method 'gfg()'
    public abstract void gfg();
     
}
 
// class 'GeeksForGeeks' inherit
// in child class 'Geek1'
public class Geek1 : GeeksForGeeks
{
 
    // abstract method 'gfg()'
    // declare here with
    // 'override' keyword
    public override void gfg()
    {
        Console.WriteLine("class Geek1");
    }
}
 
// class 'GeeksForGeeks' inherit in
// another child class 'Geek2'
public class Geek2 : GeeksForGeeks
{
 
    // same as the previous class
    public override void gfg()
    {
        Console.WriteLine("class Geek2");
    }
}
 
// Driver Class
public class main_method {
 
    // Main Method
    public static void Main()
    {
 
        // 'g' is object of class
        // 'GeeksForGeeks' class '
        // GeeksForGeeks' cannot
        // be instantiate
        GeeksForGeeks g;
 
        // instantiate class 'Geek1'
        g = new Geek1();
         
        // call 'gfg()' of class 'Geek1'
        g.gfg();
       
        // instantiate class 'Geek2' 
        g = new Geek2();
       
        // call 'gfg()' of class 'Geek2'
        g.gfg();
         
    }
}


Output

class Geek1
class Geek2

Example 2: Program to calculate the area of a square using abstract class and abstract method

C#




// C# program to calculate the area
// of a Square using abstract class
// and abstract method
using System;
 
// declare class 'AreaClass'
// as abstract
abstract class AreaClass
{
    // declare method
    // 'Area' as abstract
    abstract public int Area();
}
 
// class 'AreaClass' inherit
// in child class 'Square'
class Square : AreaClass
{
    int side = 0;
 
    // constructor
    public Square(int n)
    {
        side = n;
    }
 
    // the abstract method
    // 'Area' is overridden here
    public override int Area()
    {
        return side * side;
    }
}
 
class gfg {
 
    // Main Method
    public static void Main()
    {
        Square s = new Square(6);
        Console.WriteLine("Area  = " + s.Area());
    }
}


Output

Area  = 36

Following are some important observations about abstract classes in C# 
1) An Abstract class does not mean that it only contains abstract methods. An Abstract class can also contain non-abstract methods also.

Syntax:  

abstract class gfg
{
    public void geek()
    {
        Console.WriteLine("'geek()' is non-abstract method");
    }
}

Example:

C#




// C# program to show the working of
// the non-abstract method in the
// abstract class
using System;
 
abstract class AbstractClass {
 
    // Non abstract method
    public int AddTwoNumbers(int Num1, int Num2)
    {
        return Num1 + Num2;
    }
 
    // An abstract method which
    // overridden in the derived class
    public abstract int MultiplyTwoNumbers(int Num1, int Num2);
     
}
 
// Child Class of AbstractClass
class Derived : AbstractClass {
 
    // implementing the abstract
    // method 'MultiplyTwoNumbers'
    // using override keyword,
    public override int MultiplyTwoNumbers(int Num1, int Num2)
    {
        return Num1 * Num2;
    }
}
 
// Driver Class
class geek {
 
    // Main Method
    public static void Main()
    {
  
        // Instance of the derived class
        Derived d = new Derived();
 
        Console.WriteLine("Addition : {0}\nMultiplication :{1}",
                                          d.AddTwoNumbers(4, 6),
                                    d.MultiplyTwoNumbers(6, 4));
    }
}


Output

Addition : 10
Multiplication :24

2) Abstract class can also work with get and set accessors.

Example:

C#




// C# program to show the working
// of abstract class with the
// get and set accessors
using System;
 
abstract class absClass {
 
    protected int myNumber;
 
    public abstract int numbers
    {
        get;
        set;
    }
}
 
class absDerived : absClass {
 
    // Implementing abstract properties
    public override int numbers
    {
        get
        {
            return myNumber;
        }
        set
        {
            myNumber = value;
        }
    }
}
 
// Driver Class
class geek {
 
    // Main Method
    public static void Main()
    {
        absDerived d = new absDerived();
        d.numbers = 5;
        Console.WriteLine(d.numbers);
    }
}


Output

5

There are several advantages and disadvantages to using abstract classes in C#. Here are some of the main ones:

Advantages:

  1. Encapsulation: Abstract classes allow you to define a common set of behaviors or properties that derived classes should have, without
  2. exposing the implementation details of those behaviors or properties to the outside world. This can help you create more maintainable and flexible code.
  3. Code reuse: Abstract classes can be used as a base class for multiple derived classes, which can help reduce code duplication and improve code reuse.
  4. Polymorphism: Abstract classes can be used to achieve polymorphism, which allows you to write code that works with objects of different derived classes, as long as they all inherit from the same abstract base class.

Disadvantages:

  1. Tight coupling: Abstract classes can create tight coupling between the base class and derived classes, which can make it harder to modify the base class without affecting the derived classes.
  2. Limited inheritance: C# only allows a class to inherit from a single base class, so if you use an abstract class as a base class, you limit the ability of derived classes to inherit from other classes.
  3. Difficulty in testing: Because abstract classes cannot be instantiated directly, they can be more difficult to test than regular classes. In order to test a derived class, you may need to create a mock or stub of the abstract base class.
  4. Overall, abstract classes can be a powerful tool for creating flexible and maintainable code, but they should be used judiciously, taking into account the specific requirements of your application.


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads