这节我们讲Objective-C的super关键字,和java里的super关键字一样,也是调用父类的方法或变量。
Objects Can Call Methods Implemented by Their Superclasses
There’s another important keyword available to you in Objective-C, called super. Sending a message to super is a way to call through to a method implementation defined by a superclass further up the inheritance chain. The most common use of super is when overriding
a method.
Let’s say you want to create a new type of person class, a “shouting person” class, where every greeting is displayed using capital letters. You could duplicate the entire XYZPerson class and modify each string in each method to be uppercase, but the simplest
way would be to create a new class that inherits from XYZPerson, and just override the saySomething: method so that it displays the greeting in uppercase, like this:
@interface XYZShoutingPerson : XYZPerson
@end
@implementation XYZShoutingPerson
- (void)saySomething:(NSString *)greeting {
NSString *uppercaseGreeting = [greeting uppercaseString];
NSLog(@"%@", uppercaseGreeting);
}
@end
This example declares an extra string pointer, uppercaseGreeting and assigns it the value returned from sending the original greeting object the uppercaseString message. As you saw earlier, this will be a new string object built by converting each character in the original string to uppercase.
Because sayHello is implemented by XYZPerson, and XYZShoutingPerson is set to inherit from XYZPerson, you can call sayHello on an XYZShoutingPerson object as well. When you call sayHello on an XYZShoutingPerson, the call to [self saySomething:...] will use the overridden implementation and display the greeting as uppercase, resulting in the effective program flow shown in Figure 2-3.
Figure 2-3 Program flow for an overridden method
The new implementation isn’t ideal, however, because if you did decide later to modify the XYZPerson implementation of saySomething: to display the greeting in a user interface element rather than through NSLog(), you’d need to modify the XYZShoutingPerson
implementation as well.
A better idea would be to change the XYZShoutingPerson version of saySomething: to call through to the superclass (XYZPerson) implementation to handle the actual greeting:
@implementation XYZShoutingPerson
- (void)saySomething:(NSString *)greeting {
NSString *uppercaseGreeting = [greeting uppercaseString];
[super saySomething:uppercaseGreeting];
}
@end
The effective program flow that now results from sending an XYZShoutingPerson object the sayHello message is shown in Figure 2-4.
Figure 2-4 Program flow when messaging super