Object-C 学习笔记 多态
定义:在Java 中 多态是同一个行为具有多个不同表现形式或形态的能力。
多态就是同一个接口,使用不同的实例而执行不同操作,
继承的作用: 统一的接口,不同的实现 (多态的特性)
多态又会分为 编译阶段的多态 和 运行时的多态
代码说明:
Person 父类 定义两个方法,风别有 Girl 和 Boy 子类去重写 并且 实现自己的 方法
//
// Person.h
// 多态
//
// Created by game912 on 2019/1/8.
// Copyright © 2019年 john. All rights reserved.
//
#import <Foundation/Foundation.h>
@interface Person : NSObject
- (void)makeStatementWithWord:(NSString*)word;
- (void)haveInterview;
@end
//
// Person.m
// 多态
//
// Created by game912 on 2019/1/8.
// Copyright © 2019年 john. All rights reserved.
//
#import "Person.h"
@implementation Person
- (void)makeStatementWithWord:(NSString*)word{
NSLog(@"这里会有子类去实现");
}
- (void)haveInterview{
NSLog(@"由子类实现");
}
@end
//
// Boy.h
// 多态
//
// Created by game912 on 2019/1/8.
// Copyright © 2019年 john. All rights reserved.
//
#import <Foundation/Foundation.h>
#import "Person.h"
@interface Boy : Person
- (void)liaoMei;
@end
//
// Boy.m
// 多态
//
// Created by game912 on 2019/1/8.
// Copyright © 2019年 john. All rights reserved.
//
#import "Boy.h"
@implementation Boy
- (void)makeStatementWithWord:(NSString *)word{
NSLog(@"Boy 重写 person 方法");
}
- (void)haveInterview{
NSLog(@"Boy 重写");
}
- (void)liaoMei{
NSLog(@"Boy自定义方法 不属于 父类");
}
@end
//
// Girl.h
// 多态
//
// Created by game912 on 2019/1/8.
// Copyright © 2019年 john. All rights reserved.
//
#import <Foundation/Foundation.h>
#import "Person.h"
@interface Girl : Person
- (void)beiLiao;
@end
//
// Girl.m
// 多态
//
// Created by game912 on 2019/1/8.
// Copyright © 2019年 john. All rights reserved.
//
#import "Girl.h"
@implementation Girl
- (void)makeStatementWithWord:(NSString *)word{
//[super makeStatementWithWord:@""];
NSLog(@"Girl 重写 Person 方法");
}
- (void)haveInterview{
NSLog(@"Girl 重写");
}
- (void)beiLiao{
NSLog(@"gilr 自定义方法不是于 person");
}
@end
main
//
// main.m
// 多态
//
// Created by game912 on 2019/1/8.
// Copyright © 2019年 john. All rights reserved.
//
#import <Foundation/Foundation.h>
#import "Girl.h"
#import "Boy.h"
int main(int argc, const char * argv[]) {
@autoreleasepool {
// insert code here...
NSLog(@"Hello, World!");
Girl* girl = [Girl new];
Boy* boy = [Boy new ];
[girl makeStatementWithWord:@""];
[boy makeStatementWithWord:@""];
///id 类型: 是一个 指针 可以记录任何类型 [对象]
id interviewer = girl;
[interviewer haveInterview];///动态类型的识别(不是在编译阶段进行的, 而是在运行时进行的 )
[interviewer beiLiao];
interviewer = boy;
[interviewer haveInterview];
[interviewer beiLiao];//编译时 不会报错,运行时报错, 所以这里的动态 属于动态多态
//动态类型 静态类型
Boy* tom = [Boy new];//静态类型
id lucy = [Boy new];//动态类型
[tom beiLiao];//静态类型可以在编译时查错, 可读性高
[lucy beiLiao];//动态类型 编译时 不会查错 但是会更灵活。 可以进行容错处理*****************
// NSMutableArray* datesource = [NSMutableArray new];
// datesource addObject:<#(nonnull id)#> id 的使用
}
return 0;
}
OC 中可以使用 id 最为指针使用,可以实现 运行时的多态,,
由于 是运行是的多态 在编译阶段是 不能查错的,需要进行容错处理,
//动态类型 静态类型
Boy* tom = [Boy new];//静态类型
id lucy = [Boy new];//动态类型
[tom beiLiao];//静态类型可以在编译时查错, 可读性高
[lucy beiLiao];//动态类型 编译时 不会查错 但是会更灵活。 可以进行容错处理*****************