user1765369
user1765369

Reputation: 1405

Using both Inheritance and Composition in the same class?

I know the rule of using inheritance when there is an is-a relationship, and composition when there's a has-a relationship, but are the two mutually exclusive/replacements for one another or would there be a case where you should use both in the same class?

I've Googled a lot but only found articles explaining when you use each, rather than both.

Thanks

Upvotes: 3

Views: 1562

Answers (2)

Vikdor
Vikdor

Reputation: 24134

Decorator pattern is a classic example where the decorating class is composed of an instance to the decorated object of the same class and extends/implements the same class.

Upvotes: 4

Kukanani
Kukanani

Reputation: 758

They are not mutually exclusive. Example: Boat and Sailboat. Sailboat is-a Boat, but it has-a Sail, which other Boats may or may not have.

Upvotes: 2

Related Questions