Inheritance
A class can inherit from another class: the subclass gets all of the superclass's properties and methods, and can add new ones or override existing ones. Objective-C supports single inheritance only: every class has exactly one superclass, and the chain ends at NSObject.
NSObject
└── Vehicle
├── Car
└── BicycleA subclass
#import <Foundation/Foundation.h>
@interface Vehicle : NSObject
@property (nonatomic, copy) NSString *name;
@property (nonatomic) NSInteger wheels;
- (void)describe;
@end
@implementation Vehicle
- (void)describe {
NSLog(@"%@ has %ld wheels", self.name, (long)self.wheels);
}
@end
// Car inherits everything from Vehicle and adds a property and a method
@interface Car : Vehicle
@property (nonatomic) NSInteger seats;
- (void)honk;
@end
@implementation Car
- (void)honk {
NSLog(@"%@: beep beep!", self.name);
}
@end
int main(void) {
@autoreleasepool {
Car *car = [Car new];
car.name = @"Hatchback"; // inherited property
car.wheels = 4;
car.seats = 5; // Car's own property
[car describe]; // inherited method
[car honk]; // Car's own method
NSLog(@"seats: %ld", (long)car.seats);
}
return 0;
}Hatchback has 4 wheels
Hatchback: beep beep!
seats: 5
Overriding and super
A subclass overrides a method by implementing one with the same selector. Inside it, [super method] runs the superclass's version, so you can extend behaviour instead of replacing it:
#import <Foundation/Foundation.h>
@interface Employee : NSObject
@property (nonatomic, copy) NSString *name;
@property (nonatomic) double salary;
- (double)annualPay;
- (NSString *)summary;
@end
@implementation Employee
- (double)annualPay {
return self.salary * 12;
}
- (NSString *)summary {
return [NSString stringWithFormat:@"%@ earns %.0f a year", self.name, [self annualPay]];
}
@end
@interface Manager : Employee
@property (nonatomic) double bonus;
@end
@implementation Manager
- (double)annualPay {
return [super annualPay] + self.bonus; // extend the inherited calculation
}
- (NSString *)summary {
return [[super summary] stringByAppendingString:@" (manager)"];
}
@end
int main(void) {
@autoreleasepool {
Employee *dev = [Employee new];
dev.name = @"Ravi";
dev.salary = 4000;
Manager *lead = [Manager new];
lead.name = @"Mona";
lead.salary = 5000;
lead.bonus = 6000;
NSLog(@"%@", [dev summary]);
NSLog(@"%@", [lead summary]);
}
return 0;
}Ravi earns 48000 a year
Mona earns 66000 a year (manager)
Notice that Employee's summary calls [self annualPay]. For a Manager, self is a manager, so the overridden annualPay runs, bonus included. Methods are looked up on the actual object at run time, not on the type where the call is written.
Initializers in subclasses
A subclass with its own state adds its own initializer, which calls the superclass's designated initializer:
#import <Foundation/Foundation.h>
@interface Shape : NSObject
@property (nonatomic, copy, readonly) NSString *color;
- (instancetype)initWithColor:(NSString *)color;
- (double)area;
@end
@implementation Shape
- (instancetype)initWithColor:(NSString *)color {
self = [super init];
if (self) {
_color = [color copy];
}
return self;
}
- (double)area {
return 0;
}
@end
@interface Circle : Shape
@property (nonatomic, readonly) double radius;
- (instancetype)initWithColor:(NSString *)color radius:(double)radius;
@end
@implementation Circle
- (instancetype)initWithColor:(NSString *)color radius:(double)radius {
self = [super initWithColor:color]; // the superclass sets up color
if (self) {
_radius = radius; // then we set up our part
}
return self;
}
- (double)area {
return M_PI * self.radius * self.radius;
}
@end
int main(void) {
@autoreleasepool {
Circle *c = [[Circle alloc] initWithColor:@"teal" radius:2];
NSLog(@"a %@ circle with area %.2f", c.color, [c area]);
NSLog(@"Circle's superclass: %@", NSStringFromClass([Circle superclass]));
NSLog(@"Shape's superclass: %@", NSStringFromClass([Shape superclass]));
}
return 0;
}a teal circle with area 12.57
Circle's superclass: Shape
Shape's superclass: NSObject
Inheritance vs composition
Inheritance models an "is a" relationship: a Manager is an Employee. When the relationship is "has a" (a Car has an Engine), give the class a property instead. Cocoa itself prefers composition, delegation and categories over deep class hierarchies; you'll see why in later lessons.
| Keyword | Meaning |
|---|---|
@interface Sub : Super |
declares the superclass |
[super msg] |
run the superclass's implementation of msg |
[self msg] |
dynamic lookup, starting at the object's real class |
[obj superclass] |
the superclass at run time |
Note: There is no
finalkeyword in Objective-C: any class can be subclassed and any method overridden. Some Apple classes (likeNSString) are class clusters whose public class hides private subclasses, and subclassing them correctly is hard. Prefer categories for adding methods to those.
Test yourself
How many superclasses can an Objective-C class have?
- None
- Exactly one (except a root class)
- Up to two
- Any number
In an overriding method, what does [super annualPay] do?
- Calls the same method again (recursion)
- Runs the superclass's implementation
- Calls NSObject's method
- Creates a superclass object
Employee's summary calls [self annualPay]. For a Manager object, which annualPay runs?
- Employee's
- Manager's
- Both
- Neither: it's a compile error