Junior — Middle
What is the main purpose of using interfaces in programming?
sobes.tech AI
Answer from AI
The main purpose of using interfaces in programming is to define a contract or a set of methods that a class must implement, without specifying the actual implementation. This allows:
- To ensure abstraction and separate the declaration of behavior from its implementation.
- To create flexible and extensible architectures where different classes can implement the same interface in different ways.
- To facilitate testing and component replacement, as the code works with interfaces rather than specific classes.
In PHP, an interface is declared using the interface keyword and contains only method declarations without bodies:
interface Logger {
public function log(string $message);
}
class FileLogger implements Logger {
public function log(string $message) {
// implementation of writing to a file
}
}
Thus, interfaces help build more modular and maintainable code.