Vivek Yadav
Vivek Yadav

Reputation: 1127

How to inherit multiple class in objective C?

I have classA and ClassA inherit ClassX and access methods of classX. How can I also access the methiod of ClassY with inheritance because multiple inheritance is not possible. I dont want to create another other composition class for this.I want to use same classA for multiple inheritance.

Upvotes: 2

Views: 1459

Answers (3)

Duncan C
Duncan C

Reputation: 131418

Like Objective-C, Swift does not have multiple inheritance. Swift uses protocols and categories to give you the same sort of ability. You can define a protocol that defines a set of methods, and then you can add support for that protocol to multiple classes. You can often build support for a protocol into a category and then that category to your classes as needed.

Upvotes: 2

Luis Delgado
Luis Delgado

Reputation: 3734

As said before, multiple inheritance is not supported by the language (neither ObjC nor Swift). If you need to inherit methods/properties from multiple classes, you will need to use composition. Alternatively, what the language does allow you to do is to have a class conform to multiple protocols, which may or may not be a solution to the problem you are trying to solve.

I have come across very few cases where I thought that I really needed to have multiple inheritance, and even for those cases, they were typically resolved by employing an appropriate code design pattern (thinking about something like the Gang of Four design patterns). In essence, you want to abstract your code in such a way so that multiple inheritance is not a requirement anymore.

Upvotes: 1

Ahmed Nasser
Ahmed Nasser

Reputation: 220

There is no multiple inheritance. The only way to achieve this is by merging the two class heirarchies. Either by having ClassX inherit ClassY or ClassY inherit ClassX (then ClassA inherits the child class X or Y).

If the two classes do not by design fit into the same hierarchy, you might want to reconsider your design and the reasons why you do not want to use composition.

Upvotes: 4

Related Questions