Pergunta de entrevista da empresa Sonar

What is the difference between composition and inheritance? When would you use 1 over the other?

Resposta da entrevista

Sigiloso

8 de set. de 2025

Inheritance models an “is-a” relationship, where a class derives from another and reuses or overrides its behavior, but this creates tight coupling. Composition models a “has-a” relationship, where a class contains other objects and delegates work to them, making the design more flexible and loosely coupled. Use inheritance when there is a clear, stable hierarchy (e.g., a Dog is an Animal), and prefer composition when you want to swap or combine behaviors without rigid dependencies.