以下的几章将会讲解三个关键的概念:
多态,动态类型和动态绑定。
多态:来自不同类的对象可以定义共享相同名称的方法
Complex.h接口文件,表示程序中的复数
#import <Foundation/Foundation.h>
@interface Complex: NSObject
{
double real;
double imaginary;
}
@property double real, imaginary;
-(void) print;
-(void) setReal: (double) a andImaginary: (double) b;
-(Complex *) add: (Complex *) f;
@end
Complex.m实现文件
#import "Complex.h"
@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 setReal: real + [f real] andImaginary: imaginary + [f imaginary]];
return result;
}
@end
main.m测试程序
#import "Fraction.h"
#import "Complex.h"
int main...
{
...
Fraction *f1 = [[Fraction alloc] init];
Fraction *f2 =
[[Fraction alloc] init];
Fraction *fracResult;
Complex *c1 = [[Complex alloc] init];
Complex *c2 = [[Complex alloc] init];
Complex *compResult;
compResult = [c1 add: c2];
fracResult = [f1 add: f2];
...
}
注意,Fraction和Complex类都包含add:和print方法。
系统如何知道执行哪个方法呢?
程序运行时,知道第一条消息的接收者是一个Complex对象,因此,选择定义在Complex类中的add:方法。
前面提到,使用不同的类共享相同方法名称的能力称为多态。它能使你开发一组类,这组类中的每一个类都能相应相同的方法名。每个类的定义都封装了相应特定方法所需的代码,这就是的它肚里与其他的类定义。