What are abstract classes? Explain with suitable example.
Q.) What are abstract classes? Explain with suitable example.
Subject: Object Oriented Programming and MethodologyAbstract Classes:
In object-oriented programming, an abstract class is a class that is declared abstract—it may or may not include abstract methods. Abstract classes cannot be instantiated, but they can be subclassed. Abstract methods are declared without an implementation (without braces, and followed by a semicolon), and must be implemented in derived classes.
Example:
Consider the following example in Python:
from abc import ABC, abstractmethod
class Animal(ABC):
@abstractmethod
def make_sound(self):
pass
class Dog(Animal):
def make_sound(self):
print("Woof!")
class Cat(Animal):
def make_sound(self):
print("Meow!")
animal = Animal() # Error: Can't instantiate abstract class Animal with abstract methods
dog = Dog()
dog.make_sound() # Output: Woof!
cat = Cat()
cat.make_sound() # Output: Meow!
In this example, the Animal
class is declared as an abstract class with an abstract method make_sound
. The Dog
and Cat
classes inherit from the Animal
class and implement the make_sound
method. We cannot instantiate the Animal
class directly because it is abstract, but we can create objects of the Dog
and Cat
classes, which are concrete subclasses. When we call the make_sound
method on the dog
and cat
objects, we get the expected outputs of "Woof!" and "Meow!", respectively.
Key Points:
- Abstract classes define a common interface for subclasses, ensuring that they all implement certain methods.
- Abstract methods have no implementation in the abstract class and must be implemented in subclasses.
- Abstract classes cannot be instantiated, but they serve as blueprints for creating concrete subclasses.
- Abstract classes promote code organization and maintainability by grouping related classes and methods together.
- They facilitate polymorphism, allowing objects of different subclasses to be treated uniformly.