techmore.in

C# - Abstract Class

In C#, an abstract class is a class that cannot be instantiated directly. It is designed to serve as a base class for other classes. Abstract classes are typically used when you have a base class that should provide common functionality, but some methods need to be defined in derived classes.

Key Features of Abstract Classes:

  1. Cannot be instantiated: You cannot create an instance of an abstract class directly.
  2. Can contain abstract methods: These methods have no implementation in the abstract class and must be implemented in any derived class.
  3. Can contain non-abstract methods: The abstract class can also include methods with full implementations that can be inherited by derived classes.
  4. Can contain properties, fields, and constructors: Like a regular class, abstract classes can have these members.

Syntax:

csharp
abstract class Animal { public abstract void MakeSound(); // Abstract method public void Sleep() // Non-abstract method { Console.WriteLine("Sleeping..."); } }

Derived Class:

The class that derives from an abstract class must implement all its abstract methods.

csharp
class Dog : Animal { public override void MakeSound() // Implement abstract method { Console.WriteLine("Woof!"); } } class Cat : Animal { public override void MakeSound() // Implement abstract method { Console.WriteLine("Meow!"); } }

Usage:

You can use the abstract class as a base for polymorphism:

csharp
Animal myDog = new Dog(); myDog.MakeSound(); // Output: Woof! myDog.Sleep(); // Output: Sleeping... Animal myCat = new Cat(); myCat.MakeSound(); // Output: Meow! myCat.Sleep(); // Output: Sleeping...

Key Points:

  • Abstract vs. Interface: Abstract classes allow you to define both methods with and without implementation, while interfaces only allow method declarations.
  • Inheritance: A class can inherit only one abstract class but can implement multiple interfaces.