multiple inheritance in Objective C [duplicate]
Possible Duplicate:
Objective C multiple inheritance
Hi,
Objective C does not support multiple inheritance. I am porting the cpp code to Objective C
How to declare this definition in Objective C?
class A:protected B,protected C
{
//stmts;
}
@interface A:protected B,protected C
{
}
@end
is not possible.
No.
Not only that, all super classes are the equivalent of public classes in C++.
In Objective-C we don't use inheritance as much as in the C++ alike languages, we tend to use composition more. For example, if you have an array-like collection, you won't normally subclass NSArray
, you will create a new class that possibly uses an NSArray
as its "backing store".
There are tricks you can do to forward messages that your new class doesn't respond to to its NSArray instance variable. For example, you can override -forwardingTargetForSelector: so that any messages your object doesn't respond to are forwarded to the underlying NSArray. If you think about it, you can implement a home made multiple inheritance hack with this.
edit
An example:
If you have a class that provides array like collection functionality and you want all the NSArray methods, you can do this:
@interface MyClass : NSObject
{
@private
NSArray* backingArray;
}
// declarations of your methods
@end
@implementation MyClass
// implementations for your methods + initialisation
-(id) forwardingTargetForSelector: (SEL) aSelector
{
return backingArray;
}
@end
In reality, you never see code like this for simple cases - people always use categories. If you want to emulate multiple inheritance using this trick, you need an instance variable for each "inherited" class and the method -forwardingTargetForSelector:
needs some logic in it based on the selector to decide which object to return. This is going to be quite slow so you can optimise heavily used selectors by implementing them directly as per PeyloW's answer.
Objective-C do not support multiple inheritance, so this is not possible.
Inheritance is a "is-a" relation, one class can only have one is-a relation through inheritance. You can have several is-a relations through protocols (interfaces in Java or C# parlace, or completely abstract class in C++).
Instead of a is-a relation you can model a "has-a" relation. Any object can have any number of has-a relations. In practice you just need to have one instance variable of each class you want. For example:
@interface A : NSObject {
@private
B* _b;
C* _c;
}
// ... stuff
@end
You will need to reimplement all methods from B
and C
and call down to the contained instance variables as needed. If for example B
implements theAnswer
then you must also implement it in A
as:
-(int)theAnswer {
return [_b theAnswer];
}
It is cumbersome, but this is what you need to do when real multiple inheritance is not available.
精彩评论