C# Abstract Class (original) (raw)
Last Updated : 04 Feb, 2025
In C#, an abstract class is a class that cannot be instantiated directly. Abstract classes are used when we want to define a common template for a group of related classes but leave some methods or properties to be implemented by derived classes.
- An abstract class cannot be directly instantiated. We can only create objects of derived classes.
- Abstract methods are declared in the abstract classes but do not have implementation, derived classes are required to implement them.
- An abstract class also contains properties and fields which can be accessed by derived classes.
**Example 1:
C# `
// C# program to demonstrates the // working of abstract classses 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...
**Explanation: In the above example, the Animal class is an abstract class with an abstract property Sound and a virtual method Move(). The Cat and Dog classes inherit from Animal, overriding Sound and Move() to provide specific behaviors. In Main(), an array of Animal objects (Cat and Dog) is created, and a loop prints their sounds and movements.
Declaration of Abstract Classes
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 2: This example demonstrates the working of an abstract class.
C# `
// Abstract class working
using System;
// Abstract class BaseClass public abstract class BaseClass {
// Abstract method 'Display()'
public abstract void Display();
}
// Class Child1 inherits from BaseClass public class Child1 : BaseClass { // Implement abstract method Display() with override public override void Display() { Console.WriteLine("class Child1"); } }
// Class Child2 inherits from BaseClass public class Child2 : BaseClass { // Implement abstract method 'Display()' with override public override void Display() { Console.WriteLine("class Child2"); } }
public class Geeks {
public static void Main()
{
// Declare variable b of type BaseClass
BaseClass b;
// Instantiate Child1
b = new Child1();
// Call Display() of class Child1
b.Display();
// Instantiate Child2
b = new Child2();
// Call Display() of class Child2
b.Display();
}
}
`
Output
class Child1 class Child2
**Example 3: This example demonstrates abstract classes with both abstract and non-abstract methods, where the non-abstract method is inherited directly and the abstract method is overridden in the derived class.
C# `
// C# program to demonstrates 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
**Note: An abstract method is a method that is declared in an abstract class but has no body. Any non-abstract class that inherits the abstract class must provide the implementations for the abstract method.
**Example 4: This example demonstrates how to use an abstract class and method to calculate the area of square, with the actual implementation provided in the derived class.
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 Geeks {
// Main Method
public static void Main()
{
Square s = new Square(6);
Console.WriteLine("Area = " + s.Area());
}
}
`
**Example 5: This example demonstrates that Abstract class can also work with get and set accessors.
C# `
// C# program to demonstrates the working // of abstract class with the // get and set accessors using System;
abstract class absClass {
protected int n;
public abstract int n1
{
get;
set;
}
}
class absDerived : absClass {
// Implementing abstract properties
public override int n1
{
get
{
return n;
}
set
{
n = value;
}
}
}
// Driver Class class Geeks {
// Main Method
public static void Main()
{
absDerived d = new absDerived();
d.n1 = 5;
Console.WriteLine(d.n1);
}
}
`
Advantages
- **Encapsulation: Abstract classes allow us to define a common set of behaviors or properties that derived classes should have, without exposing the implementation details of those behaviors or properties to the outside world. This can help us to create more maintainable and flexible code.
- **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.
- **Polymorphism: Abstract classes can be used to achieve polymorphism, which allows us to write code that works with objects of different derived classes, as long as they all inherit from the same abstract base class
Disadvantages
- **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.
- **Limited inheritance: C# only allows a class to inherit from a single base class, so if we use an abstract class as a base class, we limit the ability of derived classes to inherit from other classes.
- **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, we may need to create a mock or stub of the abstract base class.