main.m
<pre name="code" class="objc">#import <Foundation/Foundation.h>
#import "SonA.h"
#import "SonB.h"
#import "Dog.h"
#import "Cat.h"
#import "Animal"
#import "Person"
int main(int argc, const charchar * 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;
}
</pre><pre name="code" class="objc">
SonA.h
#import "Father.h"
@interface SonA : Father
@end
</pre><h2><span style="font-family:Arial; font-size:14px">SonA.m</span></h2><div><span style="font-family:Arial; font-size:14px"></span><pre name="code" class="objc">#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
{
NSLog(@"I am SonB");
}
@end
Animal.h
#import <Foundation/Foundation.h>
@interface Animal : NSObject
-(void)eat;
@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 eat fish");
}
@end
Dog.h
#import "Animal.h"
@interface Dog : Animal
@end
Dog.m
#import "Dog.h"
@implementation Dog
-(void)eat
{
[super eat];
NSLog(@"Dog eat meat");
}
@end
Person.h
#import <Foundation/Foundation.h>
#import "Animal.h"
#import "Cat.h"
#import "Dog.h"
@interface Person : NSObject
-(void)feedCat:(Cat *)cat;
-(void)feeDdog:(Dog *)dog;
//参数是父类型动物类型,无论喂养什么动物,都可以满足要求,不用修改Person类,增加响应方法,这个也符合"开闭原则"
-(void)feeAnimal:(Animal *)animal;
@end
Person.m
#import "Person.h"
@implementation Person
-(void)feedCat:(Cat *)cat
{
NSLog(@"人喂猫");
[cat eat];
}
-(void)feeDdog:(Dog *)dog
{
NSLog(@"人喂狗");
[dog eat];
}
-(void)feeAnimal:(Animal *)animal
{
if ([animal isMemberOfClass:[Cat class]]) {
[animal eat];
NSLog(@"catcat");
}
if ([animal isMemberOfClass:[Dog class]]) {
[animal eat];
NSLog(@"dogdog");
}
}
@end