Junior — Middle
Can you explain what an abstract class means in object-oriented programming?
sobes.tech AI
Answer from AI
An abstract class in object-oriented programming is a class that is not intended to be instantiated directly, but serves as a base template for other classes.
Main features of an abstract class:
- Can contain both implemented methods and abstract methods (without implementation).
- Abstract methods must be implemented in subclasses.
- Allows defining a common interface and behavior for a group of related classes.
In Python, abstract classes are created using the abc module and the @abstractmethod decorator.
Example:
from abc import ABC, abstractmethod
class Animal(ABC):
@abstractmethod
def make_sound(self):
pass
class Dog(Animal):
def make_sound(self):
print("Woof")
# animal = Animal() # Error: cannot instantiate an abstract class
dog = Dog()
dog.make_sound() # Outputs: Woof
Thus, an abstract class defines a mandatory set of methods for its subclasses, ensuring interface consistency.