多态:使用不同的类共享相同方法名称的能力。
动态类型:能使程序指导执行时才确定对象所属的类。
动态绑定:
能使程序指导执行时才确定实际要调用的对象方法。
1.多态
下面是一个复数类 Complex 类的接口文件,它用于表示程序中的复数:
//复数类
#import <Foundation/Foundation.h>
@interface Complex : NSObject
@property double real, imaginary;
-(void) print;
-(void) setReal:(double) a andImaginary:(double) b;
-(Complex *) add: (Complex *) f;
@end
//Complex.m
@implementation Complex
@synthesize real, imaginary;
-(void) print
{
NSLog(@"%g + %gi", real, imaginary);
}
-(void) setReal:(double) a andImaginary:(double) b
{
real = a;
imaginary = b;
}
-(Complex *) add: (Complex *) f
{
Complex *result = [[Complex alloc] init];
result.real = real + f.real;
result.imaginary = imaginary + f.imaginary;
return result;
}
@end
int main(int argc, const char * argv[]) {
@autoreleasepool {
// insert code here...
NSLog(@"Hello, World!");
}
return 0;
}
//前面系列文章声明的Fraction 类
//定义Fraction类
@interface Fraction : NSObject
@property int numerator, denominator;
-(void)setTo:(int)n andOver:(int)d;
-(Fraction *) add: (Fraction *)f;
-(void) reduce;
-(double) convertToNum;
-(void) print;
@end
//主函数
int main(int argc, const char * argv[]) {
@autoreleasepool {
Fraction *f1 = [[Fraction alloc] init];
Fraction *f2 = [[Fraction alloc] init];
Fraction *fracResult;
Complex *c1 = [[Complex alloc] init];
Complex *c2 = [[Complex alloc] init];
Complex *compResult;
[f1 setTo:1 over:10];
[f2 setTo:2 over:15];
[c1 setReal:17.0 andImaginary:2.4];
[c2 setReal:3.5 andImaginary:3.3];
[c1 print];
[c2 print];
compResult = [c1 add: c2];
[compResult print];
[f1 print];
[f2 print];
fracResult = [f1 add: f2];
[fracResult print];
}
return 0;
}
可以注意到 Fraction 和Complex 两个类中都含有add: 和print 方法,在执行消息时系统会先确定接受消息的对象的类型,根据对象定义的方法行事对应的消息。
注意:
a.没有继承就没有多态。
b.代码的体现:父类型的指针指向子类对象。
c.好处:如果函数、方法参数中使用的是父类型,可以传入父类、子类对象。