/*
多肽:多種形態(tài)
1>沒有繼承就不會有多肽
2>代碼體現(xiàn):父類類型的指針指向子類對象
3>如果函數(shù)或者方法中使用的父類類型的參數(shù),那么可以傳入父類和子類的對象
4>局限性:
1>>父類類型的變量故黑,不能直接調(diào)用子類特有的方法咖驮,必須強轉(zhuǎn)成子類的變量類型
*/
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強轉(zhuǎn)
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(@"調(diào)用了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