Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call subclass's method from its superclass

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

Import "Parent.h" in app delegate's .m file header.

App delegate's application:didFinishLaunchingWithOptions: method..

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

[parent methodOfParent];

[parent release];
like image 810
Confused Avatar asked Sep 22 '11 13:09

Confused


3 Answers

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?

like image 67
Adam Wright Avatar answered Oct 16 '22 11:10

Adam Wright


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.

like image 6
sElanthiraiyan Avatar answered Oct 16 '22 10:10

sElanthiraiyan


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.

like image 5
helioz Avatar answered Oct 16 '22 10:10

helioz