Objective-C Simple Inheritance and OO Principles

Posted by bleeckerj on Stack Overflow See other posts from Stack Overflow or by bleeckerj
Published on 2012-12-15T17:02:03Z Indexed on 2012/12/15 17:03 UTC
Read the original article Hit count: 409

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.

© Stack Overflow or respective owner

Related posts about objective-c

Related posts about design-patterns