Chapter 6. Extending classes

 

This chapter covers

  • Subclassing
  • Extending classes
  • Creating custom objects
  • Class clusters
  • Categories
  • Existing class modification

Classes, which consist of instance variables and methods, can be extended by being modified, expanded, or abstracted. Class extension is one of the fundamental ideas of object-oriented programming. The ability to extend a class promotes code reuse and compartmentalization, and it’s the sign of a well-thought-out project. We investigate the subtleties of the various approaches to extending classes.

6.1. Subclassing

In chapter 5, you learned how to create your own classes. If you look back, you’ll see that the classes you made, such as CTRentalProperty, are subclasses of NSObject. NSObject is the most basic class that Objective-C provides. You’ll subclass NSObject many times when creating original classes for your application. This isn’t to say it’s the only class you can subclass: any class in Objective-C can be extended by subclassing. NSObject is explored in more detail later in this chapter.

6.1.1. What is subclassing?

Subclassing is the act of taking a class, with all of its methods and instance variables, and adding to it. A classic example of subclassing logic is used in taxonomy, when classifying species. A human is a mammal; a tiger is a mammal as well. Tigers and humans can both be thought of as subclasses of the mammal class because they share some common features:

  • Warm blood
  • Vertebrae
  • Hair

6.2. Adding new instance variables

6.3. Accessing existing instance variables

6.4. Overriding methods

6.5. Class clusters

6.6. Categories

6.7. Subclassing in your demo application

6.8. Summary

sitemap