[关闭]
@fiy-fish 2015-07-18T19:38:58.000000Z 字数 819 阅读 1367

day06-05-多态1

Objective-c


  1. // main.m
  2. // day06-05-多态1
  3. //
  4. // Created by Aaron on 15/7/8.
  5. // Copyright (c) 2015年 Aaron. All rights reserved.
  6. //
  7. #import <Foundation/Foundation.h>
  8. #import "Dog.h"
  9. #import "Cat.h"
  10. //多态
  11. //同一个接口,不同的实现
  12. //继承: 统一接口
  13. void animal_bark(Animal *d)
  14. {
  15. [d bark];
  16. }
  17. int main(int argc, const char * argv[]) {
  18. @autoreleasepool {
  19. Dog *d = [[Dog alloc] init];
  20. Cat *cat = [[Cat alloc] init];
  21. Animal *a = [[Animal alloc] init];
  22. [d bark];
  23. [cat bark];
  24. [a bark];
  25. animal_bark(cat);
  26. //赋值兼容原则
  27. //可以用父类的指针指向子类的对象
  28. Animal *anim = d;
  29. }
  30. return 0;
  31. }

  1. #import <Foundation/Foundation.h>
  2. @interface Animal : NSObject
  3. -(void)bark;
  4. @end

  1. #import "Animal.h"
  2. @implementation Animal
  3. -(void)bark
  4. {
  5. NSLog(@"嗷嗷嗷...");
  6. }
  7. @end

  1. #import "Animal.h"
  2. @interface Dog : Animal
  3. @end

  1. #import "Dog.h"
  2. @implementation Dog
  3. -(void)bark
  4. {
  5. NSLog(@"汪汪汪....");
  6. }
  7. @end

  1. #import "Animal.h"
  2. @interface Cat : Animal
  3. @end

  1. #import "Cat.h"
  2. @implementation Cat
  3. -(void)bark
  4. {
  5. NSLog(@"喵喵喵....");
  6. }
  7. @end

添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注