#import <Foundation/Foundation.h>
/*
1.多态的基本概念
某一类事物的多种形态
OC对象具有多态性
2.多态的体现
子类对象赋值给父类指针
父类指针访问对应的属性和方法
3.多态的好处
用父类接收参数,节省代码
4.多态的局限性
不能访问子类的属性(可以考虑强制转换)
5.多态的细节
动态绑定:在运行时根据对象的类型确定动态调用的方法
*/
/*
多态
1.没有继承就没有多态
2.代码的体现:父类类型的指针指向子类对象
3.好处:如果函数\方法参数中使用的是父类类型,可以传入父类和子类对象
4.局限性:
1>父类类型的变量 不能直接调用子类特有的方法
2>必须强制转为子类类型变量后,才能直接调用子类特有的方法
*/
//人
@interface Person : NSObject
- (void)eat;
@end
@implementation Person
- (void)eat
{
NSLog(@"person--吃");
}
@end
//学生
@interface Student : Person
- (void)walk;
@end
@implementation Student
- (void)eat
{
NSLog(@"Student--吃");
}
- (void)walk
{
NSLog(@"Student--走");
}
@end
//老师
@interface Teacher : Person
@end
@implementation Teacher
- (void)eat
{
NSLog(@"Teacher--吃");
}
@end
//如果参数中使用的是父类类型,可以传入父类,子类对象--节省代码
void dinner(Person *p)
{
[p eat];
}
int main (int argc, const char *argv[])
{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
//多种形态
Student *s = [Student new];
//多态:父类指针指向子类对象
Person *p = [Student new];
//调用方法时会检测对象的真实形象
[p eat];
Person *t = [Teacher new];
//学生吃晚饭
dinner(p);
//老师吃晚饭
dinner(t);
Person *p2 = [Student new];
//多态的局限性:父类类型的变量 不能用来调用子类的方法
//[p2 walk];
//解决方法:强制转换
Student *s2=(Student *)p2;
[s2 walk];
[pool drain];
return 0;
}
objective 多态
最新推荐文章于 2015-02-26 20:25:25 发布