多肽

/*

多肽:多种形态

1>没有继承就不会有多肽

2>代码体现:父类类型的指针指向子类对象

3>如果函数或者方法中使用的父类类型的参数,那么可以传入父类和子类的对象

4>局限性:

1>>父类类型的变量,不能直接调用子类特有的方法,必须强转成子类的变量类型

*/

main.m

#import

#import "Animal.h"

#import "Dog.h"

#import "Cat.h"


void eatanimal(Dog *d)

{

[d eat];

}


void eatanimal(Cat *c)

{

[c eat];

}


void eatanimal(Animal *a)

{

[a eat];

}


int main(int argc, const char * argv[])

{

Animal *animal = [Animal new];

Dog *dog = [dog new];

Animal *dog = [Dog new];  //  Dog吃东西

Animal *dog = [Animal new];  //  Animal吃东西

Animal *dog = [Cat new];  //  Cat吃东西

//  NSObject *dog = [Dog new];  //  报错 NSObject没有eat方法

[animal eat];

[dog eat];


Cat *cat = [Cat new];

Animal *cat = [Cat new];

[cat run];


Dog *dog = [dog new];

eatanimal(dog);


Cat *cat = [cat new];

eatanimal(cat);


Animal *animal = [animal new];

eatanimal(animal);


[dog test];

//  [animal test];  报错 animal无test方法

//  Animal *animal = [Animal new];  弱语法,Animal中无test方法,需要换成Dog强转

Animal *animal = [Dog new]; 

Dog *d = (Dog *)animal;

[d test];


return 0;

}


Animal.h

#import

@interface Animal : NSObject

- (void)eat;

- (void)run;

@end


Animal.m

#import "Animal.h"

@implementation Animal

- (void)eat

{

NSLog(@"Animal——吃东西");

}

- (void)run

{

NSLog(@"Animal——跑起来了");

}

@end


Dog.h

#import "Animal.h"

@interface Dog : Animal

- (void)eat;

- (void)test;

@end


Dog.m

#import "Dog.h"

@implementation Dog

- (void)eat

{

NSLog(@"Dog——吃东西");

}


- (void)test

{

NSLog(@"调用了test方法");

}

@end


Cat.h

#import "Dog.h"

@interface Cat : Dog

@end


Cat.m

#import "Cat.h"

@implementation Cat

- (void)eat

{

NSLog(@"Cat——吃东西");

}

- (void)run

{

NSLog(@"Cat——跑起来了");

}

@end

你可能感兴趣的:(多肽)