4.3. Containment

Containment indicates that one object contains another. Example 4-3 shows a hierarchy of contained classes, each nested within the other; the CreditCard object contains a BillingInfo object, which in turn contains an Address object.

The contained object, if it is used only within the parent object, can be declared as Private. Being restrictive (in terms of scope) at the class level is as important as being restrictive within the class itself. Don't make the class available if it is not needed. Here, Address is an object that could be used by several other classes, such as Order, ShippingInfo, or Invoice. BillingInfo is restricted to the payment and should not exist outside of it.

Example 4-3. Containment relationships
Public MustInherit Class Payment
  'Payment data
End Class
   
Public Class Address
  'Address1, Address2
  'City, ST, Zip
End Class
   
Public Class CreditCard : Inherits Payment
  
  Private Class BillingInfo
    Private myAddress As Address
    'Methods to get to address here
  End Class
  
  Private myBillingInfo As BillingInfo
   
End Class

Remember that the classes represent a has-a relationship between the parent class and the child class or classes.

The exception to this rule is the various collection classes that contain a type of an object. In this case, the container's primary behavior is to insert, remove, and maintain the objects it contains.

The same rule regarding accessibility that applies to member data also applies to a contained class; it should be private. The ...

Get Object-Oriented Programming with Visual Basic .NET now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.