01.02.2014 Views

Objective-C Fundamentals

Objective-C Fundamentals

Objective-C Fundamentals

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Subclassing in your demo application<br />

141<br />

Listing 6.13<br />

CTPeriodicLease.h<br />

#import "CTLease.h"<br />

@interface CTPeriodicLease : CTLease {<br />

float weeklyRental;<br />

}<br />

@property(nonatomic) float weeklyRental;<br />

+ (CTLease *)periodicLeaseWithWeeklyPrice:(float)weeklyPrice;<br />

@end<br />

Here a CTPeriodicLease is declared as a subclass of CTLease. A CTPeriodicLease<br />

contains a float number representing the weeklyrentalCost and provides a class<br />

method to create a CTLease object using the weekly price. Now all that’s left to do is<br />

implement the method in your main file. Use the code shown in the following listing.<br />

Listing 6.14<br />

CTPeriodicLease.m<br />

#import "CTPeriodicLease.h"<br />

@implementation CTPeriodicLease<br />

@synthesize weeklyRental;<br />

+ (CTLease *)periodicLeaseWithWeeklyPrice:(float)weeklyPrice {<br />

CTPeriodicLease *lease = [CTPeriodicLease alloc];<br />

}<br />

lease.weeklyRental = weeklyPrice;<br />

return [lease autorelease];<br />

- (NSString *)description {<br />

return [NSString stringWithFormat:@"$%0.2f per week",<br />

self.weeklyRental];<br />

}<br />

@end<br />

The creation of an object occurs B where you allocate a CTPeriodicLease object. You<br />

set the lease’s weekly rental price and return the autoreleased version of the object.<br />

One point of interest here is that this method is designated as returning a CTLease<br />

object, yet a CTPeriodicLease object is allocated and returned. The reason this is<br />

valid is that CTPeriodicLease is a subclass of CTLease, so CTPeriodicLease is a<br />

CTLease but a CTLease isn’t necessarily a CTPeriodicLease. Next, the NSObject method<br />

description is overridden. You can do this because CTPeriodicLease is also a subclass<br />

of NSObject. As you learned earlier, this technique is useful when you want<br />

objects to print their attributes out of an NSLog.<br />

6.7.3 Creating CTFixedLease as a subclass of CTLease<br />

Alloc<br />

CTPeriodicLease b<br />

You now make another CTLease subclass called CTFixedLease so you can represent a<br />

lease as having a different set of terms rather than some periodic set amount. This

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

Saved successfully!

Ooh no, something went wrong!