Alex Rivera | Logout

Differences between Java interfaces and Objective-C protocols?

Asked 2009-06-13T09:07:45.603
94

I know Java, and now I'm learning Objective-C. What exactly are the differences between Java interfaces and Objective-C protocols?

Edit
Report

1 Answer

18

They are almost identical. However the one thing that has caught me out, is that unless you explicitly declare that an objective C protocol also implements NSObject, references to that protocol don't get access to the methods that NSObject declares (without a compiler warning anyway). With java you can have a reference to an interface, and still call toString() etc on it.

eg

Objective C:

@protocol MyProtocol
// Protocol definition
@end

id <MyProtocol> myProtocol;

 [myProtocol retain] // Compiler warning

Java:

public interface MyInterface {
// interface definition
}

MyInterface myInterface;

myInterface.toString();  // Works fine.

Objective C (fixed):

@protocol MyProtocol <NSObject>
// Protocol definition
@end

id <MyProtocol> myProtocol;

[myProtocol retain] // No Warning
answered 2009-06-13T09:42:46.830

Your Answer