Sobes.tech
Junior — Middle

Can you explain what is meant by an interface in object-oriented programming?

sobes.tech AI

Answer from AI

In object-oriented programming, an interface is a set of methods that a class must implement, defining how objects interact with each other. The interface sets a contract without implementation, allowing different classes to have a common way of interaction.

In Python, interfaces can be implemented through abstract base classes (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"

Here, Animal defines the interface, and Dog and Cat implement it in their own way.