Inheritance vs Composition Interview Questions
What is the difference between inheritance and composition? When do you prefer composition? — spoken sample answer for Indian interviews.
- 5Questions with answers
- 3Difficulty levels
Questions (5)
Browse beginner, intermediate, and advanced questions with answers — hide them when you want to self-test.
What is the difference between inheritance and composition? When do you prefer composition?
Inheritance is is-a: CheckedReport is a Report. Composition is has-a: a Report has a Formatter. I prefer composition when behavior varies independently — PDF versus JSON output — because subclassing every combination becomes a tree I cannot maintain. I inject a Serializer instead of XmlReport and JsonReport subclasses. Inheritance is still right for a true taxonomy and when I need runtime polymorphism on a stable interface. 'Favor composition over inheritance' for me means default to strategy objects, not 'never extend a class'.
Give a case where inheritance hurt you.
A BaseController that grew twenty helpers. Changing the base broke children. I would compose CsvExporter and AuthFilter. Fragile base class is the name I use. I still inherit for true is-a like Exception. I would not inherit Stack from ArrayList.
How do you compose in Java or C#?
I inject behavior. OrderService gets a PricingEngine, not a GodService parent. I keep inheritance for frameworks that require it. Default: prefer composition. Exception: genuine is-a with a stable base.
Does composition avoid the diamond problem?
Yes, because I call a.foo() or b.foo() explicitly. Java forbids multiple class inheritance partly for diamonds. Interface default methods can still clash and I override. Composition is the practical escape hatch.
Is is-a always inheritance? What about Square and Rectangle?
If the base is stable and LSP holds, yes. Square as a Rectangle breaks LSP when you set width. I would make Rectangle immutable or model Square separately. Slogan is-a is not enough. LSP is the test.
Practice with AI mock interviews
Run OOP mock interviews with AI follow-ups, instant feedback, and analytics on AiLx.
Free to start · No credit card required