Junior — Middle
What consequences can occur when implementing a method inside an abstract class?
sobes.tech AI
Answer from AI
Implementing a method within an abstract class in C# allows you to define basic functionality that can be used or overridden by derived classes. This provides several advantages:
- Code reuse: common code can be written once in the abstract class.
- Partial implementation: an abstract class can contain both abstract methods (without implementation) and concrete methods with implementation.
- Flexibility: subclasses can override methods to change behavior or use the base implementation.
However, there are also consequences:
- If a method is implemented, subclasses are not required to override it, which can lead to undesirable behavior if the base implementation is not suitable.
- An abstract class cannot be instantiated directly, but its methods with implementation can be called through subclass objects.
Example:
public abstract class Animal {
public void Eat() {
Console.WriteLine("Animal eats");
}
public abstract void MakeSound();
}
public class Dog : Animal {
public override void MakeSound() {
Console.WriteLine("Bark");
}
}
Here, the Eat method is implemented in the abstract class and is available to all subclasses without mandatory overriding.