首页 / 操作系统 / Linux / Objective-C之多态学习笔记
面向对象三个基本特征就是封装、继承和多态。封装简单将就是将一组数据结构和定义在它上面的相关操作组合成一个类的过程,继承一种父子关系,子类可以拥有父类定的成员变量、属性以及方法。多态就是指父类中定义的成员变量和方法被子类继承,父类对象可以表现出不同的行为。Objective-C中的方法都是虚方法,运行时不看指针类型,根据生成对象的类型决定被调用的方法。以交通工具为例,定义父类为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
自行车 100Objective-C中@property的所有属性详解 http://www.linuxidc.com/Linux/2014-03/97744.htmObjective-C 和 Core Foundation 对象相互转换的内存管理总结 http://www.linuxidc.com/Linux/2014-03/97626.htm使用 Objective-C 一年后我对它的看法 http://www.linuxidc.com/Linux/2013-12/94309.htm10个Objective-C基础面试题,iOS面试必备 http://www.linuxidc.com/Linux/2013-07/87393.htmObjective-C适用C数学函数 <math.h> http://www.linuxidc.com/Linux/2013-06/86215.htm好学的 Objective-C 高清PDF http://www.linuxidc.com/Linux/2014-09/106226.htm本文永久更新链接地址:http://www.linuxidc.com/Linux/2014-10/108577.htm