What is the relationship between a class and an interface in objective-c? How come we declare a class using @interface
instead of @class
?
The interface
keyword such as in Java or C# is used to define a completely abstract model of an object. That is, you can only define a set of methods that an object ought to have, but absent of any kind of implementation detail.
In Objective-C,@interface
is used to the same effect. Everything inside the @interface...@end
block is also completely abstract. To implement these methods, you must do so within the @implementation...@end
block.
In other words, you could say that in Objective-C you are forced to define an interface and also a class that implements it, for every class you need and with the same name. You could do the same thing in Java or C#, were it not for the naming conflict.
Now, this separation seems unnecessary if you ever used Java or C#, but it is enforced because of how the code is compiled (Objective-C is a superset of C, like C++). You must import a class’ file in order to compile code that uses it. If every class is defined and implemented in one file each, when you import another class’s file you will import all of its imports. This would eventually lead to unsolvable circular dependencies. This is why you must define the interface of a class in a header (*.h) file, and also only import headers.
On a side note, to declare Java/C#-like interfaces in Objective-C, you can use the @protocol
block.
1