-----------android培训、java培训、java学习型技术博客、期待与您交流!-----------
OC中的多态
一、概念
多态:某一种事物的多种形态,在程序中指的是不同对象以自己的方式响应相同名称方法的能力
条件:
1、有继承关系
2、有方法重写
3、分类的声明变量指向子类对象(父类的指针指向子类的对象)
Animal *a = [Animal new];
Animal *a = [ Dgo new];
二、原理
动态绑定
1、动态类型当程序直到执行时才能确定对象所属类型
2、动态类型绑定当程序直到执行时才确定要对对象调用的方法
3、动态绑定可以在运行时加入新的数据类型和新的程序模块:动态识别、动态绑定、动态加载
4、id类型:通用指针类型,又称万能指针,弱类型,编译时不进行类型检查
#import <Foundation/Foundation.h>
//定义Animal类
@interface Animal:NSObject
-(void)run;
@end
@implementation Animal
-(void)run{
NSLog(@"动物正在跑");
}
@end
//定义Dog类
@interface Dog: Animal
@end
@implementation Dog
//重写run方法
-(void)run{
NSLog(@"狗正在迅速的奔跑!");
}
@end
int main (int argc, const char *argv[])
{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
//创建对象
Animal *a = [Animal new];
//调用run方法
[a run];
//创建dog类
Dog *d = [Dog new];
//调用run方法
[d run];
//***********使用多态时************
//创建对象
Animal *a2 = [Dog new];
// 调用方法
[a2 run];
[pool drain];
return 0;
}
三、多态特点
1、简化接口,允许在类和类之间重用一些习惯性的命名
2、可以在一个函数中考虑到所有可能的对象
四、多态的注意点
1、如果存在多态,父类是可以访问子类特有的方法
2、如果不存在多态,父类不能访问子类特有的方法
//
// main.m
// 多态
//
// Created by YuHongpeng on 15/11/8.
// Copyright (c) 2015年 YuHongpeng. All rights reserved.
//
#import <Foundation/Foundation.h>
//定义Animal类
@interface Animal:NSObject
-(void)run;
@end
@implementation Animal
-(void)run{
NSLog(@"动物正在跑");
}
@end
//定义Dog类
@interface Dog: Animal
//此方法Animal中没有
-(void)eat;
@end
@implementation Dog
//重写run方法
-(void)run{
NSLog(@"狗正在迅速的奔跑!");
}
//此方法Animal中没有
-(void)eat{
NSLog(@"狗正在吃东西!**");
}
@end
int main(int argc, const char * argv[]) {
@autoreleasepool {
// insert code here...
//————使用多态时注意————
//通过父类调用子类中有而父类中没有方法
Animal *a3 = [Dog new];
[(Dog *)a3 eat];
NSLog(@"Hello, World!");
}
return 0;
}
以下是的写法会报错