Chapter 6. Extending classes
This chapter covers
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.
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.
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