面向对象—多态练练
//有一个父亲。开了一个厂,这个厂在他手里赚了100W,但是过了几年,传到他儿子手里,经过重新装修,改良了技术后,赚了2个亿。
#import <Foundation/Foundation.h>
#import "Father.h"
#import "Sub.h"
int main(int argc, const char * argv[]) {
@autoreleasepool {
//father的变量,sub的实例
Father *father = [[Sub alloc]init];
//在运行时 father 会被转换成 sub类型
[father getInfoWithTheFactory:father];
}
return 0;
}
******父类
#import <Foundation/Foundation.h>
@interface Father : NSObject
- (void)createAFactory;
- (void)getInfoWithTheFactory:(Father *)father;
@end
@implementation Father
- (void)createAFactory
{
NSLog(@"-----------------");
NSLog(@"工厂名称:舒家猪饲料加工厂");
NSLog(@"工厂年收益:100W");
NSLog(@"厂长:舒爸");
NSLog(@"-----------------");
}
- (void)getInfoWithTheFactory:(Father *)father
{
[father createAFactory];
}
@end
**** 子类
#import "Father.h"
@interface Sub : Father
@end
@implementation Sub
//重写
- (void)createAFactory
{
NSLog(@"-----------------");
NSLog(@"工厂名称:舒家猪饲料加工厂");
NSLog(@"工厂年收益:20000W");
NSLog(@"厂长:舒");
NSLog(@"-----------------");
}
- (void)getInfoWithTheFactory:(Sub *)father
{
[father createAFactory];
}
@end