面试题答案
一键面试动态类型(Dynamic Typing)
- 概念:在Objective-C中,动态类型指的是变量的实际类型在运行时才确定,而不是编译时。这意味着一个变量可以在不同时刻指向不同类的对象,只要这些类之间存在继承关系。例如,一个指向父类的指针可以在运行时指向其子类的对象。
动态绑定(Dynamic Binding)
- 概念:动态绑定是指在运行时根据对象的实际类型来确定要调用的方法实现。在编译时,编译器只检查对象的声明类型是否有对应的方法声明,但实际调用哪个方法的实现,是在运行时根据对象的实际类型来决定的。
利用动态绑定实现多态性的示例
#import <Foundation/Foundation.h>
// 定义一个父类Animal
@interface Animal : NSObject
- (void)makeSound;
@end
@implementation Animal
- (void)makeSound {
NSLog(@"The animal makes a sound.");
}
@end
// 定义一个子类Dog,继承自Animal
@interface Dog : Animal
- (void)makeSound;
@end
@implementation Dog
- (void)makeSound {
NSLog(@"The dog barks.");
}
@end
// 定义一个子类Cat,继承自Animal
@interface Cat : Animal
- (void)makeSound;
@end
@implementation Cat
- (void)makeSound {
NSLog(@"The cat meows.");
}
@end
int main(int argc, const char * argv[]) {
@autoreleasepool {
// 声明一个Animal类型的指针
Animal *animal;
// 动态类型:指针可以指向不同类型的对象
animal = [[Dog alloc] init];
// 动态绑定:根据对象实际类型(Dog)调用对应的makeSound方法
[animal makeSound];
animal = [[Cat alloc] init];
// 动态绑定:根据对象实际类型(Cat)调用对应的makeSound方法
[animal makeSound];
}
return 0;
}
在上述代码中,animal
指针是Animal
类型,但在运行时它可以指向Dog
或Cat
类的对象。当调用makeSound
方法时,实际调用的是Dog
或Cat
类中实现的makeSound
方法,这就是通过动态绑定实现了多态性。