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

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


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.


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).


The Wikipedia entry on header files uses the same comparison with Java that you do, which is a bonus:

Some programming languages (most notably C, C++, and Objective-C) use header files. These files allow programmers to separate certain elements of a program's source code into reusable files. Header files commonly contain forward declarations of classes, subroutines, variables, and other identifiers. Programmers who wish to declare standardized identifiers in more than one source file can place such identifiers in a single header file, which other code can then include whenever the header contents are required. This is to keep the interface in the header separate from the implementation. The C standard library and C++ standard library traditionally declare their standard functions in header files.

Newer compiled languages (such as Java, C#) do not use forward declarations; identifiers are recognized automatically from source files and read directly from dynamic library symbols. This means header files are not needed.