Composition vs Inheritance | Programming Interview | Skill-Lync Resources
Medium Programming & OOP OOP Fundamentals

When should you prefer composition over inheritance?

Answer

Composition (has-a) includes objects as fields; inheritance (is-a) extends classes. Prefer composition when: relationship isn't truly is-a, you need flexibility to change behavior, avoiding deep hierarchies, reusing across unrelated classes. Inheritance problems: tight coupling, fragile base class, hierarchy explosion. Composition benefits: loose coupling, runtime flexibility, easier testing. Example: instead of Stack extending ArrayList, Stack contains ArrayList. Strategy pattern uses composition for interchangeable algorithms. 'Favor composition over inheritance' - Gang of Four.

Master These Concepts with IIT Certification
IIT Certified

Master These Concepts with IIT Certification

175+ hours of industry projects. Get placed at Bosch, Tata Motors, L&T and 500+ companies.

Relevant for Roles

Software Engineer Backend Developer Software Architect