Object C 多态

多态:使用不同的类共享相同方法名称的能力。
动态类型:能使程序指导执行时才确定对象所属的类。
动态绑定: 能使程序指导执行时才确定实际要调用的对象方法。
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.好处:如果函数、方法参数中使用的是父类型,可以传入父类、子类对象。



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值