Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Objective-C multiple inheritance

I have 2 classes one includes methodA and the other include methodB. So in a new class I need to override the methods methodA and methodB. So how do I achieve multiple inheritance in objective C? I am little bit confused with the syntax.

like image 906
Dilshan Avatar asked Nov 16 '10 08:11

Dilshan


People also ask

Does Objective C have multiple inheritance?

In keeping with its clean and simple design, Objective C does not support multiple inheritance, though features have been developed to replace some of the functionality provided by multiple inheritance (see run-time section below). The root of the Objective C class hierarchy is the Object class.

What is inheritance in Objective C?

Inheritance allows us to define a class in terms of another class which makes it easier to create and maintain an application. This also provides an opportunity to reuse the code functionality and fast implementation time.

Why Swift does not support multiple inheritance?

Swift doesn't allow us to declare a class with multiple base classes or superclasses, so there is no support for multiple inheritance of classes. A subclass can inherit just from one class. However, a class can conform to one or more protocols.


1 Answers

Objective-C doesn't support multiple inheritance, and you don't need it. Use composition:

@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 

Now you just need to invoke the method on the relevant ivar. It's more code, but there just isn't multiple inheritance as a language feature in objective-C.

like image 62
d11wtq Avatar answered Sep 21 '22 01:09

d11wtq