从父类方法调用子类的方法(Objective-c 2.0)

前端之家收集整理的这篇文章主要介绍了从父类方法调用子类的方法(Objective-c 2.0)前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有面向对象编程的经验,但出于某种原因这种情况并不熟悉.请考虑以下 Objective-c 2.0代码
  1. @interface A : NSObject
  2. @end
  3.  
  4. @implementation A
  5. - (void) f {
  6. [self g];
  7. }
  8. @end
  9.  
  10. @interface B : A
  11. @end
  12.  
  13. @implementation B
  14. - (void) g {
  15. NSLog(@"called g...");
  16. }
  17. @end

这是从父类中的方法调用子类的方法的正确方法吗?如果另一个子类没有实现方法g会发生什么?也许有更好的方法解决这个问题,就像父类A中的抽象方法一样?

解决方法

关键是在父类中有一个可以在子类中重写的方法.
  1. @interface Dog : NSObject
  2. - (void) bark;
  3. @end
  4.  
  5. @implementation Dog
  6. - (void) bark {
  7. NSLog(@"Ruff!");
  8. }
  9. @end
  10.  
  11. @interface Chihuahua : Dog
  12. @end
  13.  
  14. @implementation Chihuahua
  15. - (void) bark {
  16. NSLog(@"Yipe! Yipe! Yipe!");
  17. }
  18. @end

您会看到,您的子类将使用自己的实现覆盖父方法.您可能会看到它像这样使用:

  1. Dog *someDog = [Chihuahua alloc] init] autorelease];
  2. [someDog bark];

输出:Yipe!沮丧的声音!沮丧的声音!

猜你在找的C&C++相关文章