OC
协变(Covariance)
// 定义一个基类
@interface Animal : NSObject
- (NSString *)makeSound;
@end
@implementation Animal
- (NSString *)makeSound {
return @"Some generic animal sound";
}
@end
// 定义一个子类
@interface Dog : Animal
- (NSString *)makeSound;
@end
@implementation Dog
- (NSString *)makeSound {
return @"Woof";
}
@end
// 定义一个泛型方法
@interface Shelter : NSObject
- (Animal *)adoptAnimal; // 返回类型为 Animal,协变
@end
@implementation Shelter
- (Animal *)adoptAnimal {
return [[Dog alloc] init]; // 返回 Dog 类型的实例
}
@end
// 使用示例
Shelter *shelter = [[Shelter alloc] init];
Animal *animal = [shelter adoptAnimal];
NSLog(@"%@", [animal makeSound]); // 输出: Woof逆变(Contravariance)
总结
Last updated