Saturday, November 17, 2012

objective c protocol

Objective-C doesn't support multiple inheritance. So each class should have only one parent class. It should not have multiple parent classes for the derived class. But Objective-C supports a feature called protocol to implement multiple inheritance.

A protocol  is a list of method declarations. And if you want use those methods , you need to write the implementation for those methods.

A protocol feature in objective-C is similar to interface in Java and pure virtual function in C++.

Syntax of the protocol declaration: you need to enclose the protocol in < and > when using it.
@protocol protocolName 
//new methods
@end

//class name and protocol names separated by spaces
@interface className : parentClass <protocolName>
//class methods
@end



Example for the protocol in Objective-C:
// these are in .h file
@protocol player 
-(void) bowling;
-(void) batting;
-(void) fielding;
@end

@interface cricketPlayer : NSObject <player>
-(void) display;
@end


// this is in .m file
@implementation cricketPlayer
-(void) display
{
    NSLog(@"this is display function");
}
-(void)batting
{
    NSLog(@"this is batting");
}
-(void)bowling
{
    NSLog(@"this is bowling");
}

-(void)fielding
{
    NSLog(@"this is fielding");
}
@end


int main(int argc, const char * argv[])
{
    
    cricketPlayer *obj = [[cricketPlayer alloc] init];
    [obj display];
    [obj batting];
    [obj fielding];
    return 0;
}

From the above example protocol with name player have three methods batting, bowling and fielding. We have created a new class called cricketPlayer whos parent class is NSObject and it uses the player protocol.  So cricketPlayer's object is able to use all the methods which are available in the protocol. So now object has the properties of NSObject and protocol methods  as well.

This way you can implement multiple inheritance using protocol.

Popular Posts