Objective C多态

       面向对象的封装的三个基本特征是、继承和多态。

包是一组简单的数据结构和定义相关的操作在上面的其合并成一个类,继承1种亲子关系,子类能够拥有父类定的成员变量、属性以及方法。

       多态就是指父类中定义的成员变量和方法被子类继承,父类对象能够表现出不同的行为。

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

版权声明:本文博客原创文章。博客,未经同意,不得转载。

posted @ 2015-07-03 17:04  mengfanrong  阅读(135)  评论(0编辑  收藏  举报