3.多态
main.m
#import <Foundation/Foundation.h>
#import "SonA.h"
#import "SonB.h"
#import "Dog.h"
#import "Cat.h"
#import "Animal"
int main(int argc, const char * argv[]) {
@autoreleasepool {
#pragma mark ---------------多态--------------
/*
多态:多态就是对不同的对象响应同一个方法是做出不同的反应,它是建立在继承的基础上面
1.继承同一父类的种类,它们本身具有自己的特性
2、继承同一父类。在执行同一个命令的时候
*/
SonA *sonA=[[SonA alloc] init];
sonA.name=@"SonA";
[sonA sayHello];
SonB *sonB=[[SonB alloc] init];
sonB.name=@"SonB";
[sonB sayHello];
/*
多态的好处:
1、可以简化编程接口
允许在多个类中定义同一消息接口
具有定义一个通用的调研方法,以简化调用
2.把不同的种类对象都当做父类来看
可以屏蔽不同种类对象之间的差异,写出通用的代码
做出
*/
//1,可以简化编程接口
id animal=nil;
//由于id类型的通用性质,我们金额以将创建好的任意对象赋值给animal
animal=[Cat new];
[animal eat];
animal =[[Dog alloc] init];
[animal eat];
// Cat *cat=[[Cat alloc] init];
// 2.把不同的种类对象都作为父类
Animal *animalB=nil;
animalB=[Cat new];
[animalB eat];
animalB =[Dog new];
[animalB eat];
//开闭原则 和里氏原则
//开闭原则(Open Closed principle ,OCP)对货站开放,对秀该关闭
//里替换原则(Liskvo Substitution Principle,LSP)任何积累可以出现的地方,子类一定可以出现(基类:已存在的用来派生新类的父类,也就是基类);
Person *person=[[Person alloc] init];
Cat *cat=[Cat new];
Dog *dog=[Dog new];
[person feedCat:cat];
[person feedDog:dog];
[person feedAnimal:cat];
[person feedAnimal:dog];
}
return 0;
}
SonA.h
#import "Father.h"
@interface SonA : Father
@end
SonA.m
#import "SonA.h"
@implementation SonA
-(void)sayHello
{
[super sayHello];
NSLog(@"I am SonA");
}
@end
SonB.h
#import "Father.h"
@interface SonB : Father
@end
SonB.m
#import "SonB.h"
@implementation SonB
-(void)sayHello
{
[super sayHello];
NSLog(@"I am SonB");
}
@end
Animal.h
#import "SonB.h"
@implementation SonB
-(void)sayHello
{
[super sayHello];
NSLog(@"I am SonB");
}
@end
Animal.m
#import "Animal.h"
@implementation Animal
-(void)eat
{
NSLog(@"动物吃东西!");
}
@end
Cat.h
#import "Animal.h"
@interface Cat : Animal
@end
Cat.m
#import "Cat.h"
@implementation Cat
-(void)eat
{
[super eat];
NSLog(@"Cat eats fish!");
}
@end
Dog.h
#import "Animal.h"
@interface Dog : Animal
@end
Dog.m
#import "Dog.h"
@implementation Dog
-(void)eat
{
[super eat];
NSLog(@"Dog eats meat!!");
}
@end