Sobes.tech
Junior — Middle

What is the role of abstract classes in object-oriented programming?

sobes.tech AI

Answer from AI

Abstract classes in object-oriented programming serve to define a base template or interface for other classes. They can contain both implemented methods and abstract methods (without implementation), which must be implemented in subclasses.

Main roles of abstract classes:

  • Providing a common interface for a group of related classes.
  • Partial implementation of functionality that can be used by inheritors.
  • Prohibiting the creation of instances of the abstract class itself, as it is intended only for inheritance.

Example in Python:

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"

# animal = Animal()  # Error: cannot instantiate an abstract class

dog = Dog()
print(dog.make_sound())  # Outputs: Woof

Thus, abstract classes help structure code and ensure that key methods are overridden in subclasses.