Junior — Middle
Can you explain what abstract classes are and how they are used in object-oriented programming?
sobes.tech AI
Answer from AI
An abstract class in C# is a class that cannot be instantiated directly and serves as a base for other classes. It can contain both implemented methods and abstract methods (without implementation), which must be overridden in derived classes.
It is used to define a common interface and basic behavior, while allowing subclasses to implement specific details.
Example:
abstract class Animal
{
public abstract void MakeSound(); // abstract method
public void Sleep()
{
Console.WriteLine("Sleeps");
}
}
class Dog : Animal
{
public override void MakeSound()
{
Console.WriteLine("Bark");
}
}
// Usage
Animal dog = new Dog();
dog.MakeSound(); // Outputs "Bark"
dog.Sleep(); // Outputs "Sleeps"
Thus, abstract classes help create templates for a family of related classes, ensuring the mandatory implementation of key methods in derived classes.