从其超类调用子类的方法 [英] Call subclass's method from its superclass
问题描述
我有两个类,名为 Parent
和 Child
,如下所示。 Parent
是 Child
的超类我可以使用关键字<$ c从其子类调用超类的方法$ C>超。是否可以从其超类中调用子类的方法?
I have two classes, named Parent
and Child
, as below. Parent
is the superclass of Child
I can call a method of the superclass from its subclass by using the keyword super
. Is it possible to call a method of subclass from its superclass?
Child.h
#import <Foundation/Foundation.h>
#import "Parent.h"
@interface Child : Parent {
}
- (void) methodOfChild;
@end
Child.m
#import "Child.h"
@implementation Child
- (void) methodOfChild {
NSLog(@"I'm child");
}
@end
Parent.h:
#import <Foundation/Foundation.h>
@interface Parent : NSObject {
}
- (void) methodOfParent;
@end
Parent.m:
#import "Parent.h"
@implementation Parent
- (void) methodOfParent {
//How to call Child's methodOfChild here?
}
@end
导入 Parent.h在app delegate的.m文件头中。
Import "Parent.h" in app delegate's .m file header.
App委托的应用程序:didFinishLaunchingWithOptions:
method ..
App delegate's application:didFinishLaunchingWithOptions:
method..
Parent *parent = [ [Parent alloc] init];
[parent methodOfParent];
[parent release];
推荐答案
你可以像Objective C方法一样调度动态。只需用 [self methodOfChild]
调用它,这可能会生成编译器警告(你可以通过强制 self
来沉默到 id
)。
You can, as Objective C method dispatch is all dynamic. Just call it with [self methodOfChild]
, which will probably generate a compiler warning (which you can silence by casting self
to id
).
但是,为了善良的爱,不要这样做。父母应该为子女提供,而不是为父母提供子女。知道子类新方法的父是一个巨大的设计问题,在继承链上创建了错误的强耦合。如果父母需要它,为什么它不是父母的方法?
But, for the love of goodness, don't do it. Parents are supposed to provide for their children, not the children for their parents. A parent knowing about a sub-classes new methods is a huge design issue, creating a strong coupling the wrong way up the inheritance chain. If the parent needs it, why isn't it a method on the parent?
这篇关于从其超类调用子类的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!