What is composition in object-oriented design?
Composition builds an object from references to other objects that provide part of its state or behavior. It expresses a has-a relationship.
Study 7 Composition and Delegation with 12 free online flashcards. Review key terms, definitions, and concepts with this interactive flashcard deck.
What is composition in object-oriented design?
Composition builds an object from references to other objects that provide part of its state or behavior. It expresses a has-a relationship.
How does composition differ from inheritance?
Inheritance expresses an is-a relationship, while composition expresses a has-a relationship. A MountainBike may be a Bicycle, whereas a Bicycle has a Wheel.
What characterizes strong composition?
In strong composition, the containing object creates and controls the lifetime of its parts, such as an Order creating its own OrderLine objects.
What is dependency injection?
Dependency injection supplies a collaborator from outside, commonly through a constructor. This makes dependencies explicit, supports testing, and allows implementations to be replaced.
What is delegation?
Delegation occurs when an object receives a request but passes responsibility for carrying out the operation to another object.
What role does the main object play during delegation?
A delegating object may validate input or coordinate an operation, then call a method on its collaborator and return or combine the result.
How does composition support encapsulation?
Encapsulation means a containing object uses a component's methods or interface instead of directly modifying its private fields.
Why compose with an interface rather than a concrete class?
Depending on an interface lets the same class use different implementations, such as email, SMS, or a test notification sender.
What condition supports using inheritance?
Inheritance requires a genuine subtype whose instances can safely be used wherever the superclass is expected. This is the basis of substitutability.
When is composition usually preferable to inheritance?
Prefer composition when a relationship is has-a, uses-a, or depends-on; when behavior varies independently; or when a hierarchy would become rigid or deep.
Why should Report use rather than extend Printer?
A Report should use a Printer rather than extend Printer because a report is not a kind of printer. Composition models the relationship accurately.
How does composition implement the strategy pattern?
The strategy pattern places replaceable behavior in a collaborator and delegates an operation to it. UserAccount can therefore vary notification behavior without subclasses.