Junior — Middle
How is an interface implemented in object-oriented programming and what role does it play?
sobes.tech AI
Answer from AI
In object-oriented programming (OOP), an interface is an abstract type that defines a set of methods that a class must implement but does not contain their implementation. The interface sets a contract that guarantees objects of different classes can be used interchangeably if they implement the same interface.
In Python, interfaces are implemented through abstract base classes (ABC) from the abc module or simply by agreement on the presence of certain methods (duck typing).
Example using ABC:
from abc import ABC, abstractmethod
class Animal(ABC):
@abstractmethod
def make_sound(self):
pass
class Dog(Animal):
def make_sound(self):
return "Woof"
class Cat(Animal):
def make_sound(self):
return "Meow"
# Now, all classes implementing Animal must have the make_sound method
The role of the interface is to ensure uniform interaction with objects of different classes, facilitating code extensibility and maintenance.