开发者

Implementing run time polymorphism and inheritence

开发者 https://www.devze.com 2023-02-03 18:18 出处:网络
What is the equivalent concept of i开发者_运维百科nterface in java in objective C. I want to create a interface and define some common variables and methods which will be shared by many classes inheri

What is the equivalent concept of i开发者_运维百科nterface in java in objective C. I want to create a interface and define some common variables and methods which will be shared by many classes inheriting from my interface. When any class outside want to use a child class it will get a reference object of my interface which will point to correct child class.

How to achieve this in Objective C?


An Objective C equivalent of Java interfaces is called "protocol".

A small intro can also be found here, and if you want a full reference, it's at Apple


In Objective-C, you can achieve this by making use of Protocols. A protocol is basically the precursor to an interface in Java, so most of the behavior should come naturally.

A protocol declaration looks like the following:

@protocol Foo
-(void) foo;
-(int) boo: (int) arg;
@end

It may be implemented by a class. In the following case, you would say MyClass conforms to the Foo protocol.

@interface MyClass <Foo>
{
}

@end

@implementation MyClass

-(void) foo {
    //do something
}
-(int) boo: (int) arg {
    //do something else
    return arg;
}

@end

Finally, you can pass them around like this:

-(void) someMethod: (id<Foo>) arg;

If you need to be more specific about the object, they can also be used like this:

-(void) someMethod: (NSObject<Foo> *) arg;
0

精彩评论

暂无评论...
验证码 换一张
取 消