objective c - Why is a child class' implementation used when initialising? -


created 2 classes a , b b subclasses a. when trying init b calls [super init] why super class a use child's (b)'s implementation of printmessage ?

@implementation  - (instancetype)init {     self = [super init];     if (self) {         [self printmessage:@"foo"];     }     return self; }  -(void)printmessage:(nsstring *)message {     nslog(@"from a: %@", message); }  @end 

implementation of b (subclasses a)

@implementation b  - (instancetype)init {     self = [super init];     if (self) {         [self printmessage:@"bar"];     }     return self; }  -(void)printmessage:(nsstring *)message {     nslog(@"from b: %@", message); }  @end 

initialised using:

b *b = [[b alloc] init]

expected output:

from a: foo b: bar 

actual output:

from b: foo b: bar 

you initializing object of type b. search method implementations starts in class b , uses overridden methods if found, dropping parent implementations otherwise.

your b's printmessage have explicitly call [super printmessage: message] invoked...just call init.


try putting inside a's init clarify things:

    nslog(@"i'm %@", nsstringfromclass([self class])); 

Comments

Popular posts from this blog

javascript - Laravel datatable invalid JSON response -

java - Exception in thread "main" org.springframework.context.ApplicationContextException: Unable to start embedded container; -

sql server 2008 - My Sql Code Get An Error Of Msg 245, Level 16, State 1, Line 1 Conversion failed when converting the varchar value '8:45 AM' to data type int -