从父类方法调用子类的方法(Objective-c 2.0) [英] Calling method on child class from parent class method (Objective-c 2.0)

查看:113
本文介绍了从父类方法调用子类的方法(Objective-c 2.0)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有面向对象编程的经验,但出于某种原因这种情况并不熟悉。考虑以下Objective-c 2.0代码:

I have experience with object-oriented programming however this situation is unfamiliar for some reason. Consider the following Objective-c 2.0 code:

@interface A : NSObject
@end

@implementation A
- (void) f {
    [self g];
}
@end

@interface B : A
@end

@implementation B
- (void) g {
    NSLog(@"called g...");
}
@end

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

Is this the correct way to call a method on a child class from a method in the parent class? What happens if another child class doesn't implement method g? Perhaps there's a better way to solve this like an abstract method in the parent class A?

推荐答案

关键是在父类中有一个可以在子类中重写的方法。

The key is to have a method in the parent class that may be overriden in the child class.

@interface Dog : NSObject
- (void) bark;
@end

@implementation Dog
- (void) bark {
    NSLog(@"Ruff!");
}
@end

@interface Chihuahua : Dog
@end

@implementation Chihuahua
- (void) bark {
    NSLog(@"Yipe! Yipe! Yipe!");
}
@end

你看,你的子课将覆盖父母方法有自己的实现。您可能会看到它使用如下:

You see, your child class will override the parent method with its own implementation. You might see it used like this:

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

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

这篇关于从父类方法调用子类的方法(Objective-c 2.0)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆