Call subclass's method from its superclass

*爱你&永不变心* 提交于 2019-11-27 14:46:48

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?

Technically you can do it. But I suggest you to alter your design. You can declare a protocol and make your child class adopt that protocol. Then you can have to check whether the child adopts that protocol from the super class and call the method from the super class.

You could use this:

Parent.m

#import "Parent.h"

@implementation Parent

- (void) methodOfChild {

    // this should be override by child classes
    NSAssert(NO, @"This is an abstract method and should be overridden");    
}

@end

The parent knows about the child and child has a choice on how to implement the function.

super means "invoke a method dispatching on the parent class", so can use super in the subclass because a subclass only has one parent class. A class can have many _sub_classes though, so how would you know which method implementation to call, in the general case? (Hence there is no such thing as a sub keyword.)

However, in your example you have two separate methods. There's nothing stopping you (assuming you have very good reasons for doing something like this!) from saying, in the parent,

- (void) methodOfParent {
    [self methodOfChild];
}

if your super has multiple subs then go for this one for the specific sub's method

if ([super isKindOfClass:[specificsub class]]) {
                [specificsub methodName];
            }

if your super is dealing with that object (that sub) so sub's method loggedin will be called an other way is in you super class

super *some = [[sub alloc] init];
[some methodName];

This can be done by over riding the method in subclass. That is create a method in parent class and over ride the same in subclass.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!