C# Abstract

Abstract Class in C#

In C#, an abstract class is a class that is declared with the keyword abstract. It can have both abstract methods (methods without a body) and non-abstract methods (methods with a body). An abstract class cannot be instantiated (you can’t create an object directly from it). Instead, other classes (called derived classes) must inherit from the abstract class and provide the implementation for its abstract methods.

Key Points:

  1. Abstract Methods: Methods that are declared without a body in the abstract class. Derived classes must give these methods a body.
  2. Non-Abstract Methods: Methods with a body that can be used by the derived classes.
  3. Why Use Abstract Classes? Abstract classes help in defining common behavior (methods) for multiple classes, but let each class implement them differently.

Structure of Abstract:

abstract class MyBaseClass
{
    // Abstract method declaration
    public abstract void MyAbstractMethod();
    // Non-abstract method
    public void MyConcreteMethod()
    {
        Console.WriteLine(“This is a concrete method in the abstract class.”);
    }
}

Scenario: Create a program to simulate different pets. Each pet can make its own sound and all pets can sleep. You will use an abstract class for common behaviours and specific classes for each pet.

using System;
abstract class Animal
{
         public abstract void MakeSound();
         public void Sleep()
         {
              Console.WriteLine(“The animal is sleeping.”);
          }
}
class Dog : Animal
{
         public override void MakeSound()
        {
            Console.WriteLine(“The dog says: Woof Woof”);
         }
}
class Cat : Animal
{
          public override void MakeSound()
         {
            Console.WriteLine(“The cat says: Meow Meow”);
         }
}
class Program
{
         static void Main()
        {
        Animal myDog = new Dog();
        Animal myCat = new Cat();
        myDog.MakeSound();
        myCat.MakeSound();
        myDog.Sleep();
        myCat.Sleep();
         }
}

Explanation:

using System;

// Define an abstract class named Animal

abstract class Animal
{

// Abstract method that must be implemented by derived classes

public abstract void MakeSound();

// Concrete method that is common to all animals

public void Sleep()
    {
         Console.WriteLine(“The animal is sleeping.”);
    }  

}

// Dog class inherits from Animal

class Dog : Animal
{

// Override the MakeSound method to specify dog’s sound

    public override void MakeSound()
     {
             Console.WriteLine(“The dog says: Woof Woof”);
     }
}

// Cat class inherits from Animal

class Cat : Animal
{

// Override the MakeSound method to specify cat’s sound

       public override void MakeSound()
   {
        Console.WriteLine(“The cat says: Meow Meow”);
   }
}

// Main program class

class Program
{
       static void Main()
      {

// Create instances of Dog and Cat

Dog myDog = new Dog();
Cat myCat = new Cat();

// Call the MakeSound method for dog and cat

  myDog.MakeSound();  // Outputs: The dog says: Woof Woof
  myCat.MakeSound();  // Outputs: The cat says: Meow Meow

// Call the Sleep method for dog and cat

    myDog.Sleep(); // Outputs: The animal is sleeping.
    myCat.Sleep(); // Outputs: The animal is sleeping.
    }
}

Course Video :

Course Video English :

Task:

1. Basic Abstract Class and Method Implementation:
Create an abstract class Vehicle with an abstract method Start. Derive two classes Car and Bike from Vehicle. Implement the Start method in both derived classes to print “Car starting” and “Bike starting” respectively. In the Main method, create instances of Car and Bike and call the Start method on each.

2.  Abstract Class with Properties:
Create an abstract class Person with an abstract property Name and an abstract method GetDetails. Derive two classes Student and Teacher from Person. Implement the Name property and GetDetails method in both derived classes. In the Main method, create instances of Student and Teacher, set their names, and call the GetDetails method to print their details.

3.  Abstract Class with Constructor :
Create an abstract class Appliance with a protected constructor that takes a string parameter brand and an abstract method ShowBrand. Derive two classes WashingMachine and Refrigerator from Appliance. Implement the ShowBrand method in both derived classes to print the brand. In the Main method, create instances of WashingMachine and Refrigerator and call the ShowBrand method.

4.  Abstract Class with Multiple Methods:
Create an abstract class Shape with two abstract methods: CalculateArea and CalculatePerimeter. Derive two classes Circle and Rectangle from Shape. Implement the CalculateArea and CalculatePerimeter methods in both derived classes. In the Main method, create instances of Circle and Rectangle, set their dimensions, and call the methods to print the area and perimeter of each shape.

5.  Abstract Class and Inheritance Hierarchy:
Create an abstract class Animal with an abstract method Speak. Derive a class Mammal from Animal and override the Speak method. Further, derive two classes Dog and Cat from Mammal and provide their specific implementations of the Speak method. In the Main method, create instances of Dog and Cat and call their Speak methods.

6. Abstract Class with Virtual and Abstract Methods:
Create an abstract class Employee with a virtual method Work that prints “Working” and an abstract method GetSalary. Derive two classes FullTimeEmployee and PartTimeEmployee from Employee. Override the Work method in both derived classes to provide specific implementations and implement the GetSalary method. In the Main method, create instances of FullTimeEmployee and PartTimeEmployee and call their methods.

Frequently Asked Questions

Still have a question?

Let's talk

An abstract class in C# is a class that cannot be instantiated and is used as a base class for other classes. It can contain abstract methods with no implementation as well as fully implemented methods.

Abstract classes are used to provide a base for polymorphism and to define common behavior for derived classes.

Use the abstract keyword before the class keyword, e.g., abstract class MyBaseClass.

  • Abstract Class: Can have method implementations and fields.
  • Interface: Cannot have implementations or fields; it defines a contract.

Yes, an abstract class can contain fully implemented (non-abstract) methods.

The derived class must override the abstract method using the override keyword.

Yes, abstract classes can have constructors, but they cannot be used to instantiate the class directly.

No, C# does not support multiple inheritance for classes, whether abstract or not.

The derived class must also be declared as abstract if it does not implement all abstract methods.

No, an abstract class cannot be static because it is meant to be inherited.

Yes , Iqra Technology Academy offers free video tutorials in Hindi that explain abstract classes in C#. The tutorials provide practical examples and detailed explanations, helping you understand the concept of abstract classes and how they are used in C#.

Inheritance allows a derived class to inherit from an abstract class and implement the abstract methods defined in the base class. This enables a derived class to provide its own specific implementation of the abstract methods, while still maintaining the common structure provided by the abstract class.

Example (Inheritance and Abstract Class):

abstract class Animal

{

    public abstract void Speak();  // Abstract method

}

 

class Cat : Animal

{

    public override void Speak()

    {

        Console.WriteLine(“Cat meows”);

    }

}

 

class Program

{

    static void Main()

    {

        Animal animal = new Cat();

        animal.Speak();  // Output: Cat meows

    }

}

In this example, Cat inherits from Animal and implements the Speak() method defined as abstract in the base class.

Iqra Technology Academy offers a free online course in Hindi that covers abstract classes in C#. This course includes detailed explanations, real-life examples, and practical exercises to help you understand how abstract classes work in C# and how to apply them in your projects.

An abstract class is useful when you want to define a common interface for a group of derived classes, while still allowing each derived class to provide its own specific implementation. It helps to enforce a common structure, and it prevents direct instantiation, ensuring that objects can only be created through subclasses that provide the required behavior.

  • Abstract Class: Can have both abstract and non-abstract methods. It allows partial implementation and can hold state (fields).
  • Interface: Contains only method signatures (no implementation) and does not hold state. A class can implement multiple interfaces, but it can inherit only one abstract class.