01.02.2014 Views

Objective-C Fundamentals

Objective-C Fundamentals

Objective-C Fundamentals

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Subclassing<br />

125<br />

the only class you can subclass: any class in <strong>Objective</strong>-C can be extended by subclassing.<br />

NSObject is explored in more detail later in this chapter.<br />

6.1.1 What is subclassing?<br />

Subclassing is the act of taking a class, with all of its methods and instance variables,<br />

and adding to it. A classic example of subclassing logic is used in taxonomy, when classifying<br />

species. A human is a mammal; a tiger is a mammal as well. Tigers and humans<br />

can both be thought of as subclasses of the mammal class because they share some<br />

common features:<br />

■<br />

■<br />

■<br />

Warm blood<br />

Vertebrae<br />

Hair<br />

While tigers and humans don’t share a ton of similarities, they do share these features<br />

and, as a result, they’re both subclasses of the mammal class. This is exactly the idea<br />

that’s applied when subclassing in an object-oriented programming language. You<br />

subclass something when you want to keep everything about it and add to it. Let’s go<br />

through an example of subclassing in <strong>Objective</strong>-C.<br />

You’ll create a small iPhone application that utilizes some simple subclassing. First,<br />

you create a class called Person that describes some general attributes of a person:<br />

name, age, and gender.<br />

1 Open Xcode and create a new View-based iPhone application called PersonClass.<br />

2 Click File > New File and create a new <strong>Objective</strong>-C Class called Person as a subclass<br />

of NSObject.<br />

3 Fill in Person.h with the content of the following listing.<br />

Listing 6.1<br />

Creating the Person class<br />

#import <br />

typedef enum {<br />

Male, Female<br />

} Gender;<br />

@interface Person : NSObject {<br />

NSString *name;<br />

NSNumber *age;<br />

Gender gender;<br />

}<br />

- (id)initWithName:(NSString *)_name;<br />

- (id)initWithAge:(NSNumber *)_age;<br />

- (id)initWithGender:(Gender)_gender;<br />

- (id)initWithName:(NSString *)_name<br />

age:(NSNumber *)_age<br />

gender:(Gender)_gender;<br />

@end

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!