设为首页 加入收藏

TOP

Objective-C之多态学习笔记
2014-11-23 19:19:30 】 浏览:295
Tags: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
"Bicycle.h"
@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
#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


】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇命令行工具jdb调试Java程序 下一篇Objective-C协议初识

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目