
Inheritance and Composition
Many developers make the mistake of overusing inheritance. To avoid this mistake, keep the following in mind:
• Inheritance causes a tight coupling between classes.
• Derived classes can become overly dependant on base class implementation details. If those details
change, the derived classes can be broken.
• Only use inheritance if you can logically state, "Class A is a type of Class B."
The other flavor of code reuse is termed composition, which is used to establish the Has-A relationship. In other
words, Object A has an Object B (for example, a Car has a Radio). In code, this relationship is realized as a field
in Class A that is typed as Class B. The field can be public or private, but typically it is private. The
functionality of Class B is exposed via public members of Class A.
Consider the following class that represents Employee benefits:
public class BenefitPackage
{
public double ComputePayDeduction()
{ return 125.0; }
}
Now modify the Employee class to contain a benefits field.
public class Employee
{
// An Employee has benefits.
private BenefitPackage mBenefits = new BenefitPackage();
// Use benefits internally.
public double ComputePay()
{
return 3000.0 - mBenefits.ComputePayDeduction();
}
// Or expose certain benefit behaviors.
public double GetBenefitCost()
{
return mBenefits.ComputePayDeduction();
}
// Or expose with a property.
public BenefitPackage Benefits
{
get { return mBenefits; }
set { mBenefits = value; }
}
}
Type Casting
Table of Contents
C# Tutorial | C#.NET Tutorial | Interfaces Tutorial
Copyright (c) 2008. Intertech, Inc. All Rights Reserved. This information is to be used exclusively as an online learning aid. Any attempts to copy, reproduce, or use for training is strictly prohibited.
|
Courseware
Training Resources
Tutorials
Services