Classes
C# Abstract Classes
Abstract Classes
C# abstract classes define blueprints with abstract members.
What is an Abstract Class?
In C#, an abstract class is a class that cannot be instantiated on its own. It is meant to be a base class for other classes. Abstract classes are used to define a template for derived classes, ensuring that they implement certain methods. These methods are declared as abstract
and do not have a body in the abstract class itself.
Defining an Abstract Class
An abstract class in C# is defined using the abstract
keyword. It can contain abstract methods (methods without a body) as well as non-abstract methods (methods with a body). Here is a simple example of an abstract class:
Implementing Abstract Methods
When a class derives from an abstract class, it must implement all of the abstract methods defined in the abstract class. The derived class provides the body for these methods. Here is how you might implement the Animal
abstract class:
Why Use Abstract Classes?
Abstract classes are useful when you want to provide a common base class for related classes with a shared implementation and contract. They enforce a set of methods that derived classes must implement, promoting a consistent design.
- Abstract classes are ideal when you have some shared code and some methods that should be specified by derived classes.
- They allow you to define a common interface for a set of related classes.
Abstract Class vs Interface
While both abstract classes and interfaces are used to define contracts for classes, they serve different purposes and have different capabilities:
- Abstract Classes: Can contain fields, constructors, and methods with implementations. They are used for classes that are closely related.
- Interfaces: Can only contain method signatures and properties. They are used to define capabilities that a class should have, without deriving from a common base class.
Choosing between an abstract class and an interface depends on whether you need to provide a common base with shared code (use an abstract class), or just a contract for capabilities (use an interface).
Classes
- Classes
- Structs
- Records
- Interfaces
- Inheritance
- Abstract Classes
- Sealed Classes
- Enums
- Properties
- Previous
- Inheritance
- Next
- Sealed Classes