Multiple Inheritance in Objective C

 

Multiple Inheritance in Objective C is not supported. The reason for not supporting this mechanism might be the fact that it would have been too difficult to include in the language or the authors thought it is a bad programming and design decision. However, in various cases multiple inheritance proves to be helpful. Fortunately objective C does provide some workarounds for achieving multiple inheritance. Following are the options:

Option 1: Message Forwarding

Message Forwarding, as the name suggests, is a mechanism offered by Objective C runtime. When a message is passed to an object and the object does not respond to it, the application crashes. But before crashing the objective c runtime provides a second chance for the program to pass the message to the proper object/class which actually responds to it. After tracing for the message till the top most superclass, the forwardInvocation message is called. By overriding this method, one can actually redirect the message to another class.

Example: If there is a class named Car which has a property named carInfo which provides the car’s make, model and year of manufacture, and the carInfo contains the data in NSString format, it would be very helpful if NSString class methods could be called upon the objects of Car class which actually inherits from NSObject.

– (id)forwardingTargetForSelector:(SEL)sel

{

    if ([self.carInfo respondsToSelector:sel]) return self.carInfo;

    return nil;

}

Option 2: Composition

Composition is a cocoa design pattern which involves referencing another object and calling its functionalities whenever required. Composition actually is a technique for a view to build itself based on several other views. So, in Cocoa terminology this is very similar to Subclassing.

@interface ClassA : NSObject {

}

-(void)methodA;

@end

@interface ClassB : NSObject {

}

-(void)methodB;

@end

@interface MyClass : NSObject {

  ClassA *a;

  ClassB *b;

}

-(id)initWithA:(ClassA *)anA b:(ClassB *)aB;

-(void)methodA;

-(void)methodB;

@end

Option 3: Protocols

Protocols are classes which contains method to be implemented by other classes who implement the protocol. One class can implement as many as protocols and can implement the methods. However, with protocols only methods can be inherited and not the instance variables.

Advertisements

One thought on “Multiple Inheritance in Objective C

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s