Junior — Middle
What are the advantages and disadvantages of using interfaces in programming?
sobes.tech AI
Answer from AI
Advantages of using interfaces:
- They allow defining a contract that classes must implement, providing flexibility and extensibility.
- They support multiple inheritance of types, which classes do not.
- They ensure loose coupling between components, making testing and maintenance easier.
- They enable polymorphism — objects of different classes can be used through a common interface.
Disadvantages:
- Interfaces do not contain implementation (until default methods appeared), which can lead to code duplication.
- Changing an interface (e.g., adding new methods) can break existing implementations if default methods are not used.
- Design complexity: too many interfaces can complicate architecture.
Example:
public interface ILogger
{
void Log(string message);
}
public class ConsoleLogger : ILogger
{
public void Log(string message) {
Console.WriteLine(message);
}
}
Here, the ILogger interface defines a contract for logging, and the ConsoleLogger class implements it, allowing easy swapping of logger implementations without changing the code that uses it.