多肽

/*

多肽:多种形态

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

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

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

4>局限性:

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

*/

main.m

#import <Foundation/Foundation.h>

#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 <Foundation/Foundation.h>

@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

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 本节学习内容: 1.继承的概念 2.子类重写父类的方法 3.父类指针指向子类对象 4.多态实现 【main.m】 ...
    奔跑的小小鱼阅读 545评论 0 0
  • 继承 什么是继承? 继承是指这样一种能力,它可以使用现有类的所有功能,并在无需重新编写原来的类的情下对这些功能进行...
    AmberAlbee阅读 610评论 0 50
  • 一、封装 1. 面向对象的三大特性:封装(成员变量)、继承和多态 在OC语言中,使用@interface和@imp...
    波澜不惊的少年阅读 1,344评论 0 1
  • 多态 一.多态与类的消息(方法)机制指同一个消息(方法)根据发送的对象不同,而采用不同的行为方式//因为其他类都是...
    草根小强阅读 411评论 0 0
  • 继承 【继承】【注】这里说的继承,指集合的包含关系,即父类和子类的关系 一.认识继承(一)从生活逻辑的角度父类 ...
    草根小强阅读 1,373评论 0 0