Multi-Inheritance via protocol in OC

Source: Internet
Author: User
Tags mul

There is no concept of multiple inheritance in OC, but we can implement multiple inheritance by protocol

Examples are as follows:

#import <Foundation/Foundation.h>

@protocol ADD <NSObject>

-(int) AddA: (int) a B: (int) b;

@end

#import <Foundation/Foundation.h>

@protocol Sub <NSObject>

-(int) SubA: (int) a B: (int) b;

@end

#import <Foundation/Foundation.h>

@protocol Mul <NSObject>

-(int) Mula: (int) a B: (int) b;

@end

================================================== above is three protocols

Here is a new compute class that inherits from NSObject Calculator

#import <Foundation/Foundation.h>

#import "Add.h"

#import "Sub.h"

#import "Mul.h"

Compliance with multiple protocols

Multiple inheritance similar to C + +

@interface Calculator:nsobject <Add,Sub,Mul>

@end

#import "Calculator.h"

Implementing the methods in the Protocol

@implementation Calculator

-(int) AddA: (int) a B: (int) b {

return a+b;

}

-(int) SubA: (int) a B: (int) b {

return a-B;

}

-(int) Mula: (int) a B: (int) b {

return a*b;

}

@end

==========================================

#import <Foundation/Foundation.h>

#import "Calculator.h"

/*

Now there are multiple classes, one is the Adder class (will be counted addition) the second class is the subtraction Class (subtraction function) The third multiplier class (multiplication)

Implementing a class can be done separately-+

C + + can be implemented with multiple inheritance

But OC does not inherit much but OC can be implemented by protocol.

*/

int main (int argc, const char * argv[]) {

@autoreleasepool {

Calculator *calc = [[Calculator alloc] init];

NSLog (@ "%d", [Calc adda:1 b:1]);//2

NSLog (@ "%d", [Calc suba:1 b:1]);//0

NSLog (@ "%d", [Calc mula:1 b:1]);//1

}

return 0;

}

Multi-Inheritance via protocol in OC

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.