oc面向对象之 多态

//多态 - 在编译时和运行时所代表的对象类型是不一样的

//体现:1.只存在于继承当中

//     2.在代码中的体现是 父类指向子类的实例

//     3.好处:无视参数传递时类型的转换

//     4.super 代表当前类的实例

//oc 是一种运行时语言

//编译时 - 针对于编写代码的时候,编译工具会进行语法检查,但不会进行功能运行。

//运行时 - 针对的是编译完成后,对于功能的调用,即运行程序。

背景:

父类:Computer

         方法:showWIthGP

子类:HP

        方法: showInfo

Computer *cp = [[HP alloc]init];

 

//这里的cp在编译时和运行时所代表的对象是不同的。

//cp 在编译时指向的是父类,在运行时指向的是子类.

//        [cp showWithGP];

//为什么 无法查询到 HP 当中showInfo方法,因为,方法的查询要基于编译时的@selector的查询,它会从当前调用的对象开始,寻找,找不到就会向当前的父类寻找,一直到元类停止

        

//SEL  @selector 方法选择器 - 会去父类和本类当中去寻找方法 @selector(showInfo)

********* 父类-Animal

#import <Foundation/Foundation.h>

 

@interface Animal : NSObject

{

    @public

    int age;

    @private

    int height;

}

- (int)height;

- (void)actionWithAnimal;

- (void)showInfoWithAnimalAction:(Animal *)animal;

 

@end

 

#import "Animal.h"

 

@implementation Animal

 

- (int)height

{

    height = 10;

    return height;

}

 

- (void)actionWithAnimal

{

    NSLog(@"动物的行为");

}

//多态的表现

- (void)showInfoWithAnimalAction:(Animal *)animal

{

    [animal actionWithAnimal];

}

@end

 

***** 子类:Dog

#import <Foundation/Foundation.h>

#import "Animal.h"

@interface Dog : Animal

 

- (void)eat;

 

@end

 

#import "Dog.h"

 

@implementation Dog

 

//重写:与父类的方法名称相同且重新编写这个方法的功能

- (void)actionWithAnimal

{

//    [super actionWithAnimal]; //super 代表当前类的父类

    NSLog(@"我一只狗,可以在陆地行走%d",super.height);

}

 

- (void)eat

{

    NSLog(@"啃骨头!");

}

@end

 

posted on 2016-04-16 15:15  小|晄  阅读(61)  评论(0编辑  收藏  举报

导航