Sobes.tech
Junior — Middle

What are the differences between an abstract class and an interface in object-oriented programming?

sobes.tech AI

Answer from AI

The main differences between an abstract class and an interface in object-oriented programming:

  • Abstract class can contain both abstract (without implementation) and concrete methods (with implementation), as well as fields (state). An interface usually contains only method declarations without implementation (although some languages have default methods).

  • A class can inherit from only one abstract class (single inheritance), but can implement multiple interfaces.

  • An abstract class provides a base implementation and structure for subclasses, while an interface defines a contract that a class must adhere to.

  • An interface does not contain state, whereas an abstract class can contain fields and constructors.

Example in Python using the abc module:

from abc import ABC, abstractmethod

class AbstractClass(ABC):
    def concrete_method(self):
        print("Implementation in abstract class")

    @abstractmethod
    def abstract_method(self):
        pass

class Interface(ABC):
    @abstractmethod
    def interface_method(self):
        pass

class ConcreteClass(AbstractClass, Interface):
    def abstract_method(self):
        print("Implementation of abstract method")

    def interface_method(self):
        print("Implementation of interface method")

Here, AbstractClass contains both a concrete and an abstract method, while Interface only declares a method.