Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does Objective-C use header files instead of one-file classes like Java?

I primarily work in Java and am recently trying to learn Objective-C for Mac and iOS app development. Now, this language is quite different from what I'm used to, pointers, messages, etc, but I seem to be picking it up okay. This isn't a coding problem per say but I'd rather be properly familiar with what I'm dealing with rather than just knowing "it has to be that way just because that's how it is".

Why does the Objective-C language need header files? What is their actual purpose for being separate from the .m file? Why do functions need to be declared in the header as opposed to just implemented? Is it just one of those things that just haven't died out from an old language, or is there a real advantage as opposed to Java's one-file classes?

like image 928
Dan2552 Avatar asked Aug 10 '11 21:08

Dan2552


2 Answers

Mainly .h files exist because of downward compatibility of C - all C code is also valid Objective-C code. A C compiler works one file at a time; each file is compiled and parsed independently. The C compiler "must" have seen the declaration of a certain symbol before its first use. So, if you are using class A in B.m, at some point the compiler must have seen a declaration of A; to avoid doing things like #include "A.m" the convention is to split declarations in header files and implementation in .c, .m, .cpp... files.

Other languages such as Java will automatically scan the files in the same directory of B.java when compiling it to find the declaration of other classes; C compilers are a bit "older" and need you to #include all the necessary headers.

In short: mainly historical reasons.

like image 161
Andrea Bergia Avatar answered Sep 17 '22 20:09

Andrea Bergia


You don't have to have header files. You can have your interface and implementation in the same file, but it's easier to separate them, also makes importing classes neater, and it means other classes don't inherit a load of stuff they don't need from the .m (like constants).

like image 43
Alex Coplan Avatar answered Sep 16 '22 20:09

Alex Coplan