IOS学习笔记十(多态)
1、多态
相同类型调用同一个方法呈现多种不同的行为特征就是多态
当子类对象直接赋值给父类指针变量,父类 *p = [子类 new];,运行类型是子类,编译类型是父类,所以p不能调用子类单独实现的方法,如果子类重写了父类方法,p调用的方法会是子类重写的方法
isKindOfClass:clazz
判断该对象是否为clazz或者其子类的实例
2、测试demo
KFBase.h
#import <Foundation/Foundation.h>
#ifndef KFBase_h
#define KFBase_h
@interface KFBase : NSObject
-(void)base;
-(void)test;
@end
#endif /* KFBase_h */
KFBase.m
#import <Foundation/Foundation.h>
#import "KFBase.h"
@implementation KFBase
-(void)base
{
NSLog(@"parent base method");
}
-(void)test
{
NSLog(@"parent test method");
}
@end
SubClass.h
#import "KFBase.h"
#ifndef Subclass_h
#define Subclass_h
@interface Subclass : KFBase
-(void)sub;
-(void)test;
@end
#endif /* Subclass_h */
SubClass.m
#import <Foundation/Foundation.h>
#import "Subclass.h"
@implementation Subclass
-(void)sub
{
NSLog(@"child sub method");
}
-(void)test
{
NSLog(@"chile test method");
}
@end
main.m
#import "KFBase.h"
#import "Subclass.h"
int main(int argc, char * argv[]) {
@autoreleasepool {
KFBase *base = [KFBase new];
[base base];
[base test];
Subclass *sub = [Subclass new];
[sub base];
[sub test];
[sub sub];
KFBase *seBase = [Subclass new];
[seBase base];
[seBase test];
//下面运行会编译出错
// [seBase sub];
id dy = seBase;
[dy sub];
NSLog(@"sub是KFBase的子类吗?%d",[sub isKindOfClass:[KFBase class]]);
}
}
3、运行结果
parent base method
parent test method
parent base method
chile test method
child sub method
parent base method
chile test method
child sub method
sub是KFBase的子类吗?1
赞 (0)