Junior — Middle
In which cases is inheritance justified in object-oriented programming?
sobes.tech AI
Answer from AI
Inheritance in object-oriented programming is justified when there is an "explicit" "is-a" relationship between classes. This allows creating class hierarchies where a subclass inherits properties and methods from a base class, extending or overriding them.
Examples of inheritance usage:
- When you need to reuse the code of a base class in multiple subclasses.
- To implement polymorphism, so that objects of different classes can be processed uniformly.
- When a subclass is a specialized version of a base class.
Example in Java:
class Animal {
void sound() {
System.out.println("Some sound");
}
}
class Dog extends Animal {
@Override
void sound() {
System.out.println("Bark");
}
}
Here, Dog inherits from Animal and overrides the sound() method.