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
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();
}
}
}
OutputThe Cat goes Meow
Walking like a cat...
The Dog goes Woof
Running like a dog...
Explanation:
- Animal is declared as an abstract class, so it cannot be instantiated.
- It contains an abstract property Sound that must be implemented by all derived classes.
- It also has a virtual method Move() with a default implementation that can be overridden.
- Cat and Dog override both Sound and Move() to provide their own behavior.
- In Main, Animal references hold Cat and Dog objects, showing polymorphism.
- This demonstrates how abstract classes define a blueprint with both mandatory and optional behaviors.
Declaration of Abstract Classes
abstract class gfg{}
// class 'gfg' is abstract
Key Points
- Generally, we use abstract class at the time of inheritance.
- A derived class must use the override keyword to implement an abstract method.
- 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: Working of an abstract class.
C#
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();
}
}
Outputclass Child1
class Child2
Example 2: 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#
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' override keyword,
public override int MultiplyTwoNumbers(int Num1, int Num2){
return Num1 * Num2;
}
}
class Geek {
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));
}
}
OutputAddition: 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 3: Program to calculate the area of a Square using abstract class and abstract method
C#
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 {
public static void Main()
{
Square s = new Square(6);
Console.WriteLine("Area = " + s.Area());
}
}
Example 4: Abstract class can also work with get and set accessors.
C#
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;
}
}
}
class Geeks {
public static void Main()
{
absDerived d = new absDerived();
d.n1 = 5;
Console.WriteLine(d.n1);
}
}
Advantages
- Encapsulation: Defines common behavior without exposing implementation details.
- Code reuse: Serves as a base for multiple classes, reducing duplication.
- Polymorphism: Enables working with different derived classes through a shared base.
Disadvantages
- Tight coupling: Changes in base class can affect all derived classes.
- Limited inheritance: Only one abstract base class can be inherited.
- Testing difficulty: Cannot be instantiated directly, requiring mocks or stubs.
Explore
Introduction
Fundamentals
Control Statements
OOP Concepts
Methods
Arrays
ArrayList
String
Tuple
Indexers