objective-c - 从父类(super class)中调用子类的方法

标签 objective-c inheritance subclass superclass

我有两个类,名为 ParentChild,如下所示。 ParentChild 的父类(super class) 我可以使用关键字super 从其子类中调用父类(super class)的方法。是否可以从父类(super class)中调用子类的方法?

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

父类.m:

#import "Parent.h"

@implementation Parent

- (void) methodOfParent {

    //How to call Child's methodOfChild here?

}

@end

在 app delegate 的 .m 文件头中导入“Parent.h”。

应用委托(delegate)的 application:didFinishLaunchingWithOptions: 方法..

Parent *parent = [ [Parent alloc] init];

[parent methodOfParent];

[parent release];

最佳答案

你可以,因为 Objective C 方法分派(dispatch)是动态的。只需使用 [self methodOfChild] 调用它,这可能会生成一个编译器警告(您可以通过将 self 转换为 id 来消除警告)。

但是,看在善良的份上,请不要这样做。 parent 应该供养 child ,而不是 child 供养 parent 。了解子类新方法的父类是一个巨大的设计问题,会在继承链的错误方向上产生强耦合。如果父级需要它,为什么它不是父级的方法?

关于objective-c - 从父类(super class)中调用子类的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7515582/

相关文章:

ios - 使用 Linkedin SDK iOS 登录

java - 如何强制接口(interface)出现在所有继承级别上

inheritance - 从不扩展 Application 的类的 Main 方法启动 JavaFX

android - 如何扩展某些 Activity 以重新定位,例如onCreateOptionsMenu?

c# - 如何将同一基类的子类放入列表中?

iphone - Unity3d 和 iPhone Objective-c?

objective-c - 为什么给单例的静态变量赋了一个nil

oop - 使用的设计模式

java - 类实例变量可以从 Java 的子类中排除吗?

c++ - 对象 C 错误 : "expected unqualified-id before class pointer"