Junior — Middle
What is the role of using abstract classes in object-oriented programming?
sobes.tech AI
Answer from AI
Abstract classes in object-oriented programming serve to define a common interface and behavior for a group of related classes, while themselves cannot be instantiated directly. They allow:
- To set a base implementation of methods that can be overridden in subclasses.
- To declare abstract methods without implementation, which must be implemented by subclasses.
- To ensure uniformity and structure for class hierarchies.
Example in Java:
abstract class Animal {
abstract void makeSound();
void breathe() {
System.out.println("Breathing");
}
}
class Dog extends Animal {
@Override
void makeSound() {
System.out.println("Bark");
}
}
Here, Animal sets a general contract for all animals, and specific classes implement the particular behavior.