Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I have a custom class inherit from multiple superclasses?

I have a an iPhone app in which class A is a subclass of UIViewController:

enter image description here

Now I'm creating a new app, in which I want to re-use A, but have it subclass from B, which is fine, because B subclasses from UIViewController:

enter image description here

But now I have another class, C, which is a subclass of GLKViewController:

enter image description here

The problem comes when I try to make a third app which re-uses B without any changes. Since B inherits from UIViewController, I need to somehow tell C that it should inherit from B and from GLKViewController, which I believe is a case of multiple inheritance:

enter image description here

From what I'm reading, the best way to handle this is with composition, but I don't understand how to best apply it to my situation.

As a stand-in solution, I realized I could just create a wrapper class D which I can then modify on an app-by-app basis to subclass from the appropriate superclass for the task at hand:

enter image description here

enter image description here

But that seems kind of hacky. Is there a better way to do this?

like image 963
todd412 Avatar asked Mar 15 '13 19:03

todd412


2 Answers

Objective C only supports single inheritance. In this case you'd probably want to use protocols for common functionality. You can use a helper object to implement the protocol methods. In this case, you're not interested in whether your object is a member of a particular class, but whether it implements a specific set of methods.

like image 66
Mike C. Avatar answered Oct 19 '22 16:10

Mike C.


you can't do that in Objective-C is single inheritance -- like java or most of the other modern languages.

use a paradigm of composition or delegation

like image 28
Daij-Djan Avatar answered Oct 19 '22 17:10

Daij-Djan