Senior
Tell me about interfaces and abstract classes: when to use one, when to use the other, and inheritance features.
sobes.tech AI
Answer from AI
Interfaces and abstract classes are tools for describing contracts and basic behavior in object-oriented programming, but they have different purposes and features.
Interfaces:
- Define only method and property signatures, without implementation.
- Used to specify a mandatory set of methods that a class must implement.
- Allow multiple inheritance of contracts (where supported by the language).
- Suitable for describing roles or capabilities that can be implemented by different classes.
Abstract classes:
- Can contain both abstract methods (without implementation) and concrete methods with implementation.
- Used to create a base class with common behavior and mandatory methods for subclasses.
- Support inheritance of implementation and state (fields).
- Usually applied when there is shared logic to be divided among classes.
When to use:
- Use an interface if you need to specify only a contract without implementation.
- Use an abstract class if you need to define a common base class with partial implementation.
Inheritance features:
- A class can implement multiple interfaces.
- A class can inherit from only one abstract class (in most languages).
Example in C#:
interface ILogger
{
void Log(string message);
}
abstract class BaseLogger : ILogger
{
public abstract void Log(string message);
public void LogError(string error) {
Log("ERROR: " + error);
}
}
class ConsoleLogger : BaseLogger
{
public override void Log(string message) {
Console.WriteLine(message);
}
}
Here, the interface defines a contract, the abstract class provides partial implementation, and the concrete class implements the details.