Junior — Middle
Can you explain the meaning of interfaces in object-oriented programming?
sobes.tech AI
Answer from AI
In object-oriented programming, an interface is a contract that defines a set of methods without their implementation. Classes that implement the interface are required to provide a concrete implementation of these methods.
Interfaces allow:
- Defining common capabilities for different classes.
- Ensuring polymorphism — objects of different classes can be used through a common interface.
- Separating definition and implementation, which improves modularity and testability.
Example in C#:
public interface ILogger
{
void Log(string message);
}
public class ConsoleLogger : ILogger
{
public void Log(string message)
{
Console.WriteLine(message);
}
}
Here, ILogger defines the Log method, and the ConsoleLogger class implements this method.