← Walmart Labs Interview Insights
I knew the textbook answer but fumbled when they pushed on the 'when to use which' part.
Define inheritance and composition clearly, emphasizing that inheritance models an 'is-a' relationship while composition models a 'has-a' relationship. Then discuss trade-offs such as flexibility, coupling, and code reuse, and give a concrete example where you chose one over the other based on requirements.
Pro tip: Mention that composition is often preferred in modern software design because it avoids the fragile base class problem and supports easier testing and evolution, but acknowledge that inheritance still has valid uses when there is a true subtype relationship and behavior is stable.
Clearly state that inheritance is a mechanism where a class derives from a parent class, inheriting its properties and methods, representing an 'is-a' relationship. Composition is a design principle where a class contains instances of other classes, representing a 'has-a' relationship.
Discuss how inheritance creates tight coupling between parent and child, can lead to the fragile base class problem, and limits flexibility because a class can only inherit from one parent (in single inheritance languages). Composition offers greater flexibility, promotes loose coupling, and allows behavior to be composed dynamically at runtime.
Give a concrete example, such as a Car class inheriting from Vehicle (inheritance) versus a Car class having an Engine and Transmission (composition). Explain how the composition example allows easier swapping of components and testing.
State that inheritance is appropriate when there is a clear, stable 'is-a' relationship and you want to reuse behavior from a base class. Composition is preferable when you need flexibility, want to avoid deep hierarchies, or when the relationship is 'has-a' or 'uses-a'.
Tie your answer to a project or system design context, such as designing a payment system at Walmart Labs, where you might use composition to combine different payment methods and avoid a rigid inheritance hierarchy.
AI-generated suggestions, not part of the candidate's original notes. May be inaccurate — verify before relying on them.