[关闭]
@fiy-fish 2015-07-18T19:48:46.000000Z 字数 1278 阅读 1275

day06-05-多态-偷吃

Objective-c


  1. // main.m
  2. // 偷吃
  3. //
  4. // Created by Aaron on 15/7/8.
  5. // Copyright (c) 2015年 Aaron. All rights reserved.
  6. //
  7. #import <Foundation/Foundation.h>
  8. //2.幼儿园老师问,谁偷吃了苹果?
  9. //孩子类回答说不知道
  10. //女孩类回答 是他偷吃了
  11. //男孩类回答 不是我
  12. #import "Teacher.h"
  13. #import "Boy.h"
  14. #import "Girl.h"
  15. #import "Child.h"
  16. int main(int argc, const char * argv[]) {
  17. @autoreleasepool {
  18. Teacher *t = [[Teacher alloc] init];
  19. Boy *b = [[Boy alloc] init];
  20. // [t askToBoy:b];
  21. Girl *g = [[Girl alloc] init];
  22. [t askToChild:g];
  23. }
  24. return 0;
  25. }
  26. //继承的作用2: 统一接口(不是最常用的)
  27. //继承的作用3: 当我们觉得官方的类或者第三方的类库不太适用的时候,我们可以继承这些类,然后添加自己的属性和方法
  28. //OC是单继承
  29. //类簇不能继承

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

  1. #import "Child.h"
  2. @implementation Child
  3. -(void)answerToTeacher
  4. {
  5. NSLog(@"不知道");
  6. }
  7. @end

  1. #import "Child.h"
  2. @interface Girl : Child
  3. @end

  1. #import "Girl.h"
  2. @implementation Girl
  3. -(void)answerToTeacher
  4. {
  5. NSLog(@"是他吃的");
  6. }
  7. @end

  1. #import <Foundation/Foundation.h>
  2. #import "Child.h"
  3. @interface Teacher : NSObject
  4. //-(void)askToBoy:(Boy *)b;
  5. -(void)askToChild:(Child *)c;
  6. @end

  1. #import "Teacher.h"
  2. @implementation Teacher
  3. //-(void)askToBoy:(Boy *)b
  4. //{
  5. // NSLog(@"谁偷吃了苹果?");
  6. // [b boyAnswer];
  7. //}
  8. -(void)askToChild:(Child *)c
  9. {
  10. NSLog(@"谁偷吃了苹果?");
  11. [c answerToTeacher];
  12. }
  13. @end

  1. #import "Child.h"
  2. @interface Boy : Child
  3. //-(void)boyAnswer;
  4. @end

  1. #import "Boy.h"
  2. @implementation Boy
  3. //-(void)boyAnswer
  4. //{
  5. // NSLog(@"不是我");
  6. //}
  7. -(void)answerToTeacher
  8. {
  9. NSLog(@"不是我");
  10. }
  11. @end

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