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.

126 CHAPTER 6 Extending classes<br />

This is a very simple class that has instance variables (ivars) that all people share. Every<br />

person has a name, age, and gender. Let’s subclass the Person class by making<br />

Teacher and Student classes.<br />

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

of Person, as shown in the following listing.<br />

Listing 6.2<br />

Creating the Teacher class<br />

#import <br />

#import "Person.h"<br />

@interface Teacher: Person {<br />

NSArray *classes;<br />

NSNumber *salary;<br />

NSString *areaOfExpertise;<br />

}<br />

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

age:(NSNumber *)_age<br />

gender:(Gender)_gender<br />

classes:(NSArray *)_classes<br />

salary:(NSNumber *)_salary<br />

areaOfExpertise:(NSString *)_areaOfExpertise;<br />

@end<br />

Next, click File > New File and create a new <strong>Objective</strong>-C Class called Student as a subclass<br />

of Person, as shown in the following listing.<br />

Listing 6.3<br />

Creating the Student class<br />

#import <br />

#import "Person.h"<br />

@interface Student: Person {<br />

NSArray *classes;<br />

NSNumber *numberOfCredits;<br />

NSString *major;<br />

}<br />

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

age:(NSNumber *)_age<br />

gender:(Gender)_gender<br />

classes:(NSArray *)_classes<br />

numberOfCredits:(NSNumber *)_numberOfCredits<br />

major:(NSString *)_major;<br />

@end<br />

Now you’ve created your Teacher and Student classes as subclasses of Person. A<br />

Teacher object now has a name, age, and gender, as defined in Person, but it is<br />

extended by adding a list of classes, salary, and area of expertise. Similarly, a Student<br />

has a name, age, and gender as well as a list of classes, a number of credits, and a<br />

major. In this example, the superclass of both Teacher and Student is Person. The

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

Saved successfully!

Ooh no, something went wrong!