OC面向对象-多态

from : http://www.cnblogs.com/wendingding/p/3705428.html

其实多态说白了就是:定义类型和实际类型,一般是基于接口的形式实现的。

例子:

Animal类

//
//  Animal.h
//  WDDDuotaiTest
//
//  Created by LiuChanghong on 15/9/24.
//  Copyright © 2015年 LiuChanghong. All rights reserved.
//

#import <Foundation/Foundation.h>

@interface Animal : NSObject

-(void)eat;

@end
Animal.h
//
//  Animal.m
//  WDDDuotaiTest
//
//  Created by LiuChanghong on 15/9/24.
//  Copyright © 2015年 LiuChanghong. All rights reserved.
//

#import "Animal.h"

@implementation Animal

-(void)eat{
    NSLog(@"动物吃东西");
}

@end
Animal.m

Dog类

//
//  Dog.h
//  WDDDuotaiTest
//
//  Created by LiuChanghong on 15/9/24.
//  Copyright © 2015年 LiuChanghong. All rights reserved.
//

#import "Animal.h"

@interface Dog : Animal

//重写eat方法
-(void)eat;

@end
Dog.h
//
//  Dog.m
//  WDDDuotaiTest
//
//  Created by LiuChanghong on 15/9/24.
//  Copyright © 2015年 LiuChanghong. All rights reserved.
//

#import "Dog.h"

@implementation Dog

-(void)eat{
    NSLog(@"狗吃东西");
}

@end
Dog.m

Cat类

//
//  Cat.h
//  WDDDuotaiTest
//
//  Created by LiuChanghong on 15/9/24.
//  Copyright © 2015年 LiuChanghong. All rights reserved.
//

#import "Animal.h"

@interface Cat : Animal

//重写eat方法
-(void)eat;

@end
cat.h
//
//  Cat.m
//  WDDDuotaiTest
//
//  Created by LiuChanghong on 15/9/24.
//  Copyright © 2015年 LiuChanghong. All rights reserved.
//

#import "Cat.h"

@implementation Cat

-(void)eat{
    NSLog(@"猫吃东西");
}

@end
Cat.m

测试程序

//
//  main.m
//  WDDDuotaiTest
//
//  Created by LiuChanghong on 15/9/24.
//  Copyright © 2015年 LiuChanghong. All rights reserved.
//

#import <Foundation/Foundation.h>
#import "Animal.h"
#import "Dog.h"
#import "Cat.h"

int main(int argc, const char * argv[]) {
    @autoreleasepool {
        
        Animal *animal = [Animal new];
        [animal eat];
        
        Dog *doggg = [Dog new];
        [doggg eat];
        
        Cat *cattt = [Cat new];
        [cattt eat];
        
        //多态 父类指针指向子类对象
        Animal *dog = [Dog new];
        //动态监测 调用方法时会检测对象的真实类型
        [dog eat];
    
        
        Animal *cat = [Cat new];
        [cat eat];
        
        NSObject *object = [Animal new];
//        [object eat];//没有eat方法
        
        Animal *object_Animal = (Animal*)object;//使用强制转换,这里object和object_Animal指向的是同一个Animal对象
        [object_Animal eat];
        
    }
    return 0;
}
测试程序

输出

多态使用总结:

(1)没有继承就没有多态

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

(3)好处:如果函数方法参数中使用的是父类类型,则可以传入父类和子类对象,而不用再去定义多个函数来和相应的类进行匹配了。

(4)局限性:父类类型的变量不能直接调用子类特有的方法,如果必须要调用,则必须强制转换为子类特有的方法。

 

原文地址:https://www.cnblogs.com/liuchanghong/p/4837781.html