← Back to OOP
OOP

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.

Question 1
Interview Intermediate
Question

What is the difference between inheritance and composition? When do you prefer composition?

Answer:

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'.

Question 2
Interview Intermediate
Question

Give a case where inheritance hurt you.

Answer:

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.

Question 3
Interview Beginner
Question

How do you compose in Java or C#?

Answer:

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.

Question 4
Interview Intermediate
Question

Does composition avoid the diamond problem?

Answer:

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.

Question 5
Interview Advanced
Question

Is is-a always inheritance? What about Square and Rectangle?

Answer:

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