Polymorphism
Polymorphism means "many shapes": code written against a general type works with any object that responds to the right messages. In Objective-C this comes in two flavours: polymorphism through inheritance, and duck typing through id, because every message is looked up at run time.
Through a common superclass
#import <Foundation/Foundation.h>
@interface Animal : NSObject
@property (nonatomic, copy) NSString *name;
- (instancetype)initWithName:(NSString *)name;
- (NSString *)sound;
- (void)speak;
@end
@implementation Animal
- (instancetype)initWithName:(NSString *)name {
self = [super init];
if (self) { _name = [name copy]; }
return self;
}
- (NSString *)sound { return @"..."; }
- (void)speak {
NSLog(@"%@ says %@", self.name, [self sound]);
}
@end
@interface Dog : Animal
@end
@implementation Dog
- (NSString *)sound { return @"Woof"; }
@end
@interface Cat : Animal
@end
@implementation Cat
- (NSString *)sound { return @"Meow"; }
@end
@interface Fish : Animal
@end
@implementation Fish
@end
int main(void) {
@autoreleasepool {
NSArray *pets = @[[[Dog alloc] initWithName:@"Rex"],
[[Cat alloc] initWithName:@"Tom"],
[[Fish alloc] initWithName:@"Nemo"]];
for (Animal *pet in pets) {
[pet speak]; // one call, three behaviours
}
}
return 0;
}Rex says Woof
Tom says Meow
Nemo says ...
The loop only knows it has Animals. Each object answers sound with its own override; Fish didn't override it, so it inherits the default.
Static type vs dynamic type
The type you write in a declaration (the static type) is what the compiler checks. The class the object really has (its dynamic type) decides which method runs.
#import <Foundation/Foundation.h>
@interface Shape : NSObject
- (double)area;
- (NSString *)name;
@end
@implementation Shape
- (double)area { return 0; }
- (NSString *)name { return @"shape"; }
@end
@interface Square : Shape
@property (nonatomic) double side;
@end
@implementation Square
- (double)area { return self.side * self.side; }
- (NSString *)name { return @"square"; }
@end
@interface Triangle : Shape
@property (nonatomic) double base;
@property (nonatomic) double height;
@end
@implementation Triangle
- (double)area { return self.base * self.height / 2; }
- (NSString *)name { return @"triangle"; }
@end
double totalArea(NSArray *shapes) {
double total = 0;
for (Shape *s in shapes) {
total += [s area];
}
return total;
}
int main(void) {
@autoreleasepool {
Square *sq = [Square new];
sq.side = 3;
Triangle *tri = [Triangle new];
tri.base = 4;
tri.height = 5;
Shape *general = sq; // static type Shape, dynamic type Square
NSLog(@"general is a %@ with area %.1f", [general name], [general area]);
NSLog(@"total area: %.1f", totalArea(@[sq, tri, [Shape new]]));
}
return 0;
}general is a square with area 9.0
total area: 19.0
Duck typing with id
id means "any object". The compiler lets you send any message that some class declares, and the runtime figures out the rest. Two unrelated classes can therefore be used interchangeably if they respond to the same messages:
#import <Foundation/Foundation.h>
@interface Invoice : NSObject
- (NSString *)printableText;
@end
@implementation Invoice
- (NSString *)printableText { return @"Invoice #1042: 99.00 EUR"; }
@end
@interface Ticket : NSObject
- (NSString *)printableText;
@end
@implementation Ticket
- (NSString *)printableText { return @"Ticket: Row F, Seat 12"; }
@end
void printAll(NSArray *items) {
for (id item in items) {
if ([item respondsToSelector:@selector(printableText)]) {
NSLog(@"PRINT: %@", [item printableText]);
} else {
NSLog(@"skipping an object that can't be printed");
}
}
}
int main(void) {
@autoreleasepool {
printAll(@[[Invoice new], [Ticket new], @42]);
}
return 0;
}PRINT: Invoice #1042: 99.00 EUR
PRINT: Ticket: Row F, Seat 12
skipping an object that can't be printed
Invoice and Ticket share no superclass besides NSObject, yet printAll handles both. The respondsToSelector: check protects against objects (like the NSNumber @42) that don't understand the message.
Tip: Duck typing is flexible but unchecked. The cleaner way to say "any object that can print itself" is a protocol:
NSArray<id<Printable>> *. Protocols are covered later in this course and give you the flexibility with compiler checks.
Polymorphism in Foundation
You use polymorphism constantly without noticing. description, isEqual:, hash and compare: are overridden by many classes, so generic code like NSLog(@"%@", obj) or [array sortedArrayUsingSelector:@selector(compare:)] works for strings, numbers and dates alike:
#import <Foundation/Foundation.h>
int main(void) {
@autoreleasepool {
NSArray *values = @[@"text", @3.5, @[@"a", @"b"]];
for (id value in values) {
NSLog(@"%@ -> %@", NSStringFromClass([value superclass]), [value description]);
}
NSLog(@"%ld", (long)[@"apple" compare:@"banana"]);
NSLog(@"%ld", (long)[@10 compare:@2]);
}
return 0;
}NSString -> text
NSFloatingPointNumber -> 3.5
GSArray -> (a, b)
-1
1
compare: returns an NSComparisonResult: -1 (ascending order), 0 (same) or 1 (descending order). Some of the printed superclass names (here NSFloatingPointNumber and GSArray) are private classes behind Foundation's class clusters. They differ between Apple's Foundation and GNUstep (and between OS versions), so never write code that depends on them.
Test yourself
Animal *a = [Dog new]; [a sound]; Which sound runs?
- Animal's
- Dog's
- Neither
- It doesn't compile
What does id mean?
- An integer identifier
- A pointer to any Objective-C object
- A class object
- nil
What does [@10 compare:@2] return?
- -1 (NSOrderedAscending)
- 0 (NSOrderedSame)
- 1 (NSOrderedDescending)
- 8