@fiy-fish
2015-07-18T19:38:58.000000Z
字数 819
阅读 1386
Objective-c
// main.m
// day06-05-多态1
//
// Created by Aaron on 15/7/8.
// Copyright (c) 2015年 Aaron. All rights reserved.
//
#import <Foundation/Foundation.h>
#import "Dog.h"
#import "Cat.h"
//多态
//同一个接口,不同的实现
//继承: 统一接口
void animal_bark(Animal *d)
{
[d bark];
}
int main(int argc, const char * argv[]) {
@autoreleasepool {
Dog *d = [[Dog alloc] init];
Cat *cat = [[Cat alloc] init];
Animal *a = [[Animal alloc] init];
[d bark];
[cat bark];
[a bark];
animal_bark(cat);
//赋值兼容原则
//可以用父类的指针指向子类的对象
Animal *anim = d;
}
return 0;
}
#import <Foundation/Foundation.h>
@interface Animal : NSObject
-(void)bark;
@end
#import "Animal.h"
@implementation Animal
-(void)bark
{
NSLog(@"嗷嗷嗷...");
}
@end
#import "Animal.h"
@interface Dog : Animal
@end
#import "Dog.h"
@implementation Dog
-(void)bark
{
NSLog(@"汪汪汪....");
}
@end
#import "Animal.h"
@interface Cat : Animal
@end
#import "Cat.h"
@implementation Cat
-(void)bark
{
NSLog(@"喵喵喵....");
}
@end