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
Post a Comment