Free Trial

Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.


  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • DownloadDownload
  • PrintPrint
Share this Page URL
Help

Chapter 13. Classes and OOP > Subclassing and Derivation - Pg. 287

Classes and OOP 287 This is all rather nice, but what if there is no instance nearby for us to use? What if in the above example, we had not created the myInstance object? Well, then we would not have been able to invoke myMethod() then. Does this ever happen? The answer is yes and comes into play in Section 13.9 below. Such situations require the invocation of a base class method from the method of a derived class. We've already seen it once, in the "Creating a Subclass" subsection of Section 13.1. Composition Once a class is defined, the goal is to use it as a model programmatically, embedding this object throughout your code, intermixing use with other data types and the logical flow of execution. There are two ways of utilizing classes in your code. The first is composition. This is where different classes are mingled with and into other classes for added functionality and code reusability. You may per- haps create instances of your class inside a larger class, containing other attributes and methods enhancing the use of the original class object. The other way is with derivation and discussed in the next section. For example, let us imagine an enhanced design of the address book class we created at the be- ginning of the chapter. If, during the course of our design, we created separate classes for names, addresses, etc., we would want to integrate that work into our AddrBookEntry class, rather than have to redesign each of those supporting classes. We have the added advantages of time and effort saved, as well as more consistent code--when bugs are fixed in that same piece of code, that change is reflected in all the applications which reuse that code. Such as a class would perhaps contain Name and Phone instances, not to mention others like StreetAddress, Phone (home, work, telefacsimile, pager, mobile, etc.), Email (home, work, etc.), and possibly a few Date instances (birthday, wedding, anniversary, etc.). Here is a simple