Junior — Middle
What are the main differences between an interface and a class in object-oriented programming?
sobes.tech AI
Answer from AI
The interface and class in object-oriented programming have the following key differences:
-
Purpose:
- An interface defines a set of methods and properties without implementation, serving to describe a contract that a class must fulfill.
- A class is a concrete implementation that can contain both data (fields) and methods with implementation.
-
Implementation:
- An interface does not contain method implementations (until C# 8.0, after which default implementations appeared).
- A class contains implementations for all its methods.
-
Inheritance:
- A class can inherit from only one base class but can implement multiple interfaces.
- An interface can inherit from multiple other interfaces.
-
Usage:
- Interfaces are used to ensure polymorphism and loose coupling.
- Classes create objects and contain logic.
Example in C#:
interface ILogger
{
void Log(string message);
}
class ConsoleLogger : ILogger
{
public void Log(string message)
{
Console.WriteLine(message);
}
}
Here, ILogger is an interface, and ConsoleLogger is a class implementing this interface.