Prepin
Log in

What distinguishes inheritance from composition?

Approach / Explanation

This question is designed to evaluate your grasp of two fundamental principles in object-oriented programming (OOP): inheritance and composition. Although both concepts relate to the relationships between classes, they operate differently and are applied in distinct situations. In your response, you should clearly define each term, followed by a comparison of their functions, objectives, and consequences.

Suggested Answer

Inheritance is a method that allows the creation of a new class based on an existing class. Essentially, the new class inherits the attributes and behaviors of the original class, which promotes reusability and facilitates the addition of new features to the existing class. This establishes an "is-a" relationship. For example, if we define a class called "Animal" and another class called "Dog," we can assert that "Dog is an Animal." This concept is particularly relevant in situations where there is a class hierarchy. In contrast, composition is a design approach in object-oriented programming where a class consists of other classes, signifying a "has-a" relationship. In simple terms, composition involves one class containing or incorporating one or more classes. For instance, a car "has an" engine, which exemplifies this concept. Composition offers greater flexibility as it allows for modifications to class members without impacting other classes, thereby enhancing the robustness of the system.

Alternative Answer

Both Inheritance and Composition illustrate relationships between classes, but they fulfill different roles in object-oriented design and have their own advantages and disadvantages. Inheritance is mainly utilized to enhance the functionality of a class, adhering to an "is-a" relationship. It embodies an object-oriented principle where a child class inherits properties and methods from a parent class. This approach is effective for promoting code reuse and establishing hierarchical relationships. However, it can occasionally result in complicated and unwieldy class hierarchies. Conversely, Composition signifies a "has-a" relationship among classes. It facilitates the creation of complex types by combining objects from other classes. Due to the flexibility it provides, modifications to component classes can be made without affecting the composite class. This makes Composition an excellent method for managing complexity when modeling flat-structured objects that do not rely on hierarchies. Nevertheless, it may lead to a proliferation of individual classes when compared to inheritance.

Question Details

Difficulty & Category

Medium
concept

Companies

Canva

Product

For CandidatesFor RecruitersCompaniesBrowse JobsInterview QuestionsDeep ProfileSkill AssessmentOpportunity Matching
Prepin.ai

© 2026 Prepin LLC · Philadelphia, PA · All rights reserved.