Objective C多态

来源:互联网 发布:淘宝助理 同步宝贝 编辑:程序博客网 时间:2024/04/30 09:45

       面向对象三个基本特征就是封装、继承和多态。封装简单将就是将一组数据结构和定义在它上面的相关操作组合成一个类的过程,继承一种父子关系,子类可以拥有父类定的成员变量、属性以及方法。

       多态就是指父类中定义的成员变量和方法被子类继承,父类对象可以表现出不同的行为。OC中的方法都是虚方法,运行时不看指针类型,根据生成对象的类型决定被调用的方法。

       以交通工具为例,定义父类为Vehicle,两个子类Bicycle、Car都继承自它,都拥有父类的成员变量name、属性height以及实例方法run

“Vehicle.h”@interface Vehicle : NSObject{    NSString *name;}@property(assign, nonatomic)int weight;-(void)run;@end<span style="font-family:SimHei;">"Bicycle.h"</span>@interface Bicycle : Vehicle@end"Car.h"@interface Car : Vehicle@end
       分别实现Car和Bicycle中的run方法

@implementation Bicycle-(void)run{        name=@"自行车";    self.weight=100;    NSLog(@"%@ %d", name , self.weight);}@end

@implementation Car-(void)run{    name=@"汽车";    self.weight=2000;    NSLog(@"%@ %d", name, self.weight);}@end

          在main.m中测试

#import <Foundation/Foundation.h>#import "Vehicle.h"#import "Car.h"#import "Bicycle.h"int main(int argc, const char * argv[]){    @autoreleasepool {        Car *car=[[Car alloc]init];                Bicycle *bike=[[Bicycle alloc]init];                Vehicle *veh=car;        [car run];        veh = bike;        [veh run];    }    return 0;}

运行结果为:汽车 2000
                      自行车 100

0 0
原创粉丝点击