Abstract Class in C# with Method and Examples

Learn via video courses
Topics Covered

Overview

Abstract classes in C# provide a powerful mechanism for implementing abstraction, a fundamental principle in software development. Abstraction allows us to define common characteristics and behaviors of related classes while hiding their specific implementations. Abstract classes serve as blueprints for derived classes, providing a foundation for code reusability and structure. By declaring methods as abstract within an abstract class, we can enforce derived classes to provide their own implementations.

What is Abstraction in C#?

Abstraction in C# is a fundamental concept that allows developers to represent complex real-world entities in a simplified and manageable way. It involves capturing the essential features and behaviors of an object while hiding unnecessary details. By abstracting away implementation specifics, abstraction provides a high-level view of an object's functionality.

Use Cases

Abstraction in C# finds its application in various scenarios, including:

  • Modelling Systems: Abstraction allows developers to represent complex systems and entities in a simplified manner. It helps in creating a conceptual model that focuses on the key aspects and behaviors, making the code more understandable and maintainable.
  • Designing Frameworks: Abstraction plays a crucial role in designing frameworks. By defining abstract classes and interfaces, it provides a clear and well-defined interface for users to interact with the framework's functionalities. This abstraction layer hides the underlying implementation details, allowing developers to modify and extend the framework without affecting the clients.
  • Implementing Design Patterns: Abstraction is instrumental in implementing design patterns such as the Factory Method pattern or the Template Method pattern. These patterns rely on abstract classes and interfaces to define common behaviors and provide a structure for flexible implementation.

Abstract Method in C#

An abstract method in C# is a method that is declared in an abstract class but does not contain any implementation. It serves as a placeholder for derived classes to provide their own unique implementations. Abstract methods define a contract or requirement that derived classes must fulfill. They are used to enforce specific behavior in derived classes while allowing flexibility in implementation details.

Syntax

The syntax for declaring an abstract method in C# is as follows:

  • The access-modifier determines the visibility of the abstract method (e.g., public, protected, etc.).
  • The abstract keyword is used to mark the method as abstract.
  • The return-type specifies the data type that the method should return.
  • nMethodName is the name of the abstract method.
  • parameters represent any input parameters required by the method.

Examples

Here are a couple of examples to illustrate the usage of abstract methods:

Example 1: Abstract method in an abstract class representing a Shape:

Output:

In this example, we have an abstract class Shape, which contains an abstract method CalculateArea(). The Shape class also includes a non-abstract method Display() for displaying a generic message.

Two derived classes, Circle and Rectangle, inherit from the Shape class. Each derived class provides its own implementation of the CalculateArea() method, specific to its shape.

Example 2: Abstract method in an abstract class representing a Bank Account:

Output:

In this example, we have an abstract class BankAccount, representing a bank account with an abstract method Withdraw() for withdrawing money. Two derived classes, SavingsAccount and CheckingAccount, inherit from the BankAccount class and provide their own implementations for the Withdraw() method.

Abstract Classes in C#

Abstract class in C# serve as a foundation for creating related classes and cannot be instantiated themselves. They provide a way to define common behavior, properties, and methods that derived classes can inherit and implement. Abstract classes can contain both abstract (unimplemented) and non-abstract (implemented) members, allowing for a combination of shared functionality and specific implementations.

Syntax

The syntax for declaring an abstract class in C# is as follows:

The abstract keyword is used to mark the class as abstract. The class can then include various members, such as abstract methods, non-abstract methods, properties, fields, and events.

Examples

Example 1: Abstract class representing an Animal:

Output:

In this example, we have an abstract class Animal, representing an animal with an abstract method Sound() for making the animal sound. The class also includes a non-abstract method Eat() for indicating the animal is eating.

Two derived classes, Dog and Cat, inherit from the Animal class. Each derived class provides its own implementation for the Sound() method, representing the specific sound of the animal.

Example 2: Abstract class representing a Shape with different derived shapes.

Output:

In this example, we have an abstract class Vehicle, representing a vehicle with an abstract method Start() for starting the vehicle. The class also includes a non-abstract method Stop() for indicating that the vehicle has stopped.

Two derived classes, Car and Motorcycle, inherit from the Vehicle class. Each derived class provides its own implementation for the Start() method, specific to the vehicle type.

Important Observations about Abstract Class in C#

When working with abstract classes in C#, there are several important observations to consider. These observations help in understanding the behavior and usage of abstract classes effectively.

  • Abstract classes cannot be directly instantiated.
  • Derived classes must implement all abstract methods.
  • Abstract classes can have both abstract and non-abstract members.
  • Abstract classes can be used as reference types for polymorphism.
  • Modifying an abstract class can impact all derived classes.
  • Abstract classes are designed to serve as blueprints for related classes.

Advantages of Abstract Class in C#

Abstract classes in C# offer several advantages that contribute to the robustness and flexibility of code development. Here are some key advantages of using abstract classes:

  • Encourages code reusability: Abstract classes allow you to define common behavior, properties, and methods that can be inherited by multiple derived classes.
  • Provides a blueprint for derived classes: Abstract classes serve as a blueprint or template for derived classes.
  • Enables polymorphism and inheritance: Abstract classes facilitate polymorphism, allowing derived classes to be treated as instances of the abstract class.
  • Defines contracts through abstract methods: Abstract classes use abstract methods to define contracts that derived classes must implement.
  • Supports code organization and modularity: Abstract classes provide a way to organize code and promote modularity.
  • Enables future extensibility: Abstract classes are designed to be extended by derived classes.

Disadvantages of Abstract Class in C#

While abstract classes offer various advantages, they also come with certain disadvantages. It is essential to consider these limitations when deciding whether to use abstract classes in your code. Here are some disadvantages of abstract classes in C#:

  • Limited inheritance: In C#, a class can inherit from only one abstract class. This limitation restricts the ability to inherit from multiple abstract classes or other types simultaneously.
  • Tight coupling: Abstract classes create a level of coupling between the base abstract class and its derived classes. This means that changes made to the abstract class can potentially impact all derived classes.
  • Incomplete implementation: Abstract classes often include abstract methods, which must be implemented in derived classes.
  • Limited flexibility: Once an abstract class is defined, its structure and contracts are more rigid compared to interfaces.
  • Object-oriented design concerns: In some cases, abstract classes may violate certain principles of object-oriented design, such as the Single Responsibility Principle (SRP) or the Interface Segregation Principle (ISP).

FAQs

Q. Can an abstract class have a constructor?

A. Yes, an abstract class can have a constructor.

Q. Can a class be both abstract and sealed?

A. No, a class cannot be both abstract and sealed.

Q. Can abstract methods have a body in an abstract class?

A. No, abstract methods in an abstract class do not have a body.

Conclusion

  • Abstract classes in C# allow for the creation of blueprints or templates that define common behavior and structure for derived classes.
  • Abstract methods within abstract classes establish contracts that derived classes must fulfill by providing their own implementations.
  • Abstract classes cannot be directly instantiated; they serve as a base for derived classes.
  • Abstract classes promote code reusability, modularity, and extensibility.
  • Polymorphism can be achieved by treating derived classes as instances of the abstract class, enabling flexibility in code design.
  • While abstract classes offer advantages such as code organization and contract enforcement, they also come with limitations, such as tight coupling and limited inheritance.