Junior — Middle
In which cases is it recommended to use an abstract class in object-oriented programming?
sobes.tech AI
Answer from AI
An abstract class in object-oriented programming is recommended to be used when:
- You need to define a common interface and a basic implementation for a group of related classes.
- The class itself should not be instantiated directly, but only serve as a template for subclasses.
- It is important that all subclasses implement certain methods (which are declared as abstract).
For example, if you have a class Animal with an abstract method makeSound(), then specific animals (dogs, cats) will inherit this class and implement the method in their own way.
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("Woof");
}
}
Thus, an abstract class helps organize code by ensuring the implementation of key methods in subclasses and allowing the use of common implementation parts.