Objective-C Simple Inheritance and OO Principles
- by bleeckerj
I have a subclass SubClass that inherits from baseclass BaseClass.
BaseClass has an initializer, like so:
-(id)init {
self = [super init];
if(self) {
[self commonInit];
}
return self;
}
-(void)commonInit {
self.goodStuff = [[NSMutableArray alloc]init];
}
SubClass does its initializer, like so:
-(id)init {
self = [super init];
if(self) {
[self commonInit];
}
return self;
}
-(void)commonInit {
self.extraGoodStuff = [[NSMutableArray alloc]init];
}
Now, I've *never taken a proper Objective-C course, but I'm a programmer more from the Electrical Engineering side, so I make do. I've developed server-side applications mostly in Java though, so I may be seeing the OO world through Java principles.
When SubClass is initialized, it calls the BaseClass init and my expectation would be — because inheritance to me implies that characteristics of a BaseClass pass through to SubClass — that the commonInit method in BaseClass would be called during BaseClass init.
It is not. I can *sorta understand maybe-possibly-stretch-my-imagination why it wouldn't be. But, then — why wouldn't it be based on the principles of OOP? What does "self" represent if not the instance of the class of the running code?
Okay, so — I'm not going to argue that what a well-developed edition of Objective-C is doing is wrong. So, then — what is the pattern I should be using in this case? I want SubClass to have two main bits — the goodStuff that BaseClass has as well as the extraGoodStuff that it deserves as well.
Clearly, I've been using the wrong pattern in this type of situation. Am I meant to expose commonInit (which makes me wonder about encapsulation principles — why expose something that, in the Java world at least, would be considered "protected" and something that should only ever be called once for each instance)?
I've run into a similar problem in the recent past and tried to muddle through it, but now — I'm really wondering if I've got my principles and concepts all straight in my head.
Little help, please.