#686 – Inheritance vs. Containment

You can think of inheritance as white box reuse of existing code, meaning that a derived class can see some aspects of the internals of the base class.  This violates the principle of encapsulation, which states that the implementation details of a class are hidden from any code that uses the class.

There is another method of code reuse known as containment, which results in black box reuse of existing code.  Instead of deriving from a base class, the new class just creates an instance of the class internally and accesses only the public members of the instance.  The instance of the base class can be thought of as a black box, because the derived class doesn’t have access to the implementation details of the base class.

About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

3 Responses to #686 – Inheritance vs. Containment

  1. geoffmazeroff says:

    I hope there’s a future post coming about the difference between containment and composition. Those always confuse me.

  2. Pingback: #687 – An Example of Containment « 2,000 Things You Should Know About C#

  3. Pingback: #688 – Aggregation, Composition and Containment « 2,000 Things You Should Know About C#

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s