Object-oriented programming · interview question
In Java, why might composition be preferred over inheritance when designing a class to calculate discounts for different product categories?
Multiple choiceEasychapter-5-curatedpremiumoopcomposition-vs-inheritance
Answer and explanation
Correct answer
D. It allows for more flexible reuse of code.
Why
Composition allows you to reuse and change behaviors by composing objects with different implementations. This flexibility enables you to extend or change functionality without modifying existing code, adhering to the open/closed principle.
Test yourself on Object-oriented programming
A free test with instant, explained results. No account needed.
More Object-oriented programming questions
- What happens if a subclass does not implement all abstract methods from its abstract superclass?
- What does the 'this' keyword refer to within an instance method of a class?
- Which Java keyword would you use to declare an abstract class in Java?
- Which statement correctly creates an instance of the 'Product' class?
- How does using interfaces in Java promote flexibility in application design?
- What issue might arise from using deep inheritance hierarchies?