|
|
Language Fundamentals - Source Files
A Java source code file or compilation unit has three basic parts, each of which is optional (JLS §7.3):
- A package declaration
- import declarations
- top-level class and interface declarations
Package declaration
- if used, it must be the first non-comment statement in the source code file
- you can not declare more than one
- syntax: package packageName;
Import declarations
- if used, must be the first non-comment statement directly following the package declaration.
- you can use as many import statements as you want
- if no package statement appears in the source code file, the import statement must be the first non-comment statement in the file
top-level class and interface declarations
- A top-level class or interface is defined as any class or interface whose declaration is not contained within the body of any other class or interface declaration. (JLS §8 and §9).
- you can declare multiple classes and interfaces within a file with the following caveats:
- The Sun SDK allows one and only one public class or interface within a source code file.
- The filename must exactly match the name of the public class or interface declared in the file and have the .java extension
| Non-public classes may have main() methods. If they have no access modifier (package access) they may still be run from the command-line using the classname.
|
Example Code
Tips
- an empty source file will compile without error
- if a
.java file does not contain a public class or interface it can have any name
Traps
- code with package or import declarations given in wrong order
- more than one package declaration
- file with more than one public class or interface declaration
- filename.java does not match public class name as declared within the file
|