Junior — Middle
When and why is it appropriate to use abstract classes in object-oriented programming?
sobes.tech AI
Answer from AI
Abstract classes in C# are used when you need to define a base class that specifies a common interface and behavior for a group of subclasses, but should not instantiate objects of the base class itself. They allow for partially implementing common functionality while leaving implementation details to subclasses.
Use an abstract class if:
- There is a common set of methods and properties that all subclasses should have.
- You want to provide some default implementation that can be overridden.
- You want to prevent the class from being instantiated directly.
Example:
abstract class Animal
{
public abstract void MakeSound(); // method that must be implemented
public void Sleep() // common method with implementation
{
Console.WriteLine("Sleeping...");
}
}
class Dog : Animal
{
public override void MakeSound()
{
Console.WriteLine("Bark bark");
}
}
Here, Animal is an abstract class that defines a contract and partial implementation, while Dog implements specific behavior.