Java Source File Declaration Rules Explained
Understanding the declaration rules for Java source files is essential when writing Java programs. These rules ensure that code is structured clearly, readable, and conforms to the syntax requirements of the Java language. Below are detailed explanations of these rules:
1. File Name
- File name must match the public class name: If the source file contains a public class (
public class), the file name must exactly match the class name (case-sensitive) and end with.java.- For example,
public class MyClassshould be saved in a file namedMyClass.java.
- For example,
2. Package Declaration
-
Package declaration: If the class belongs to a package, it must be declared on the first line of the source file. The format is: ``` package packageName;
-
Position of package declraation: It must appear at the top of the file, immediately after any file comments if present.
3. Import Declarations
-
Importing other classes: Use
importstatements to include other classes or packages for use within the current class. The format is: ``` import packageName.ClassName; -
Importing all classes: Use an asterisk (
*) to import all classes from a package: ``` import packageName.*; -
Position of import declarations: They must come after the package declaration and before the class declaration.
4. Class Declaration
-
Class declaration: The format for declaring a class is: ``` public class ClassName {
// class content}
-
Access modifiers: Classes can use access modifiers (such as
public,protected,private) to control their visibility.
5. Multiple Classes
- One public class per file: A source file can contain multiple classes, but only one can be public.
- Non-public classes: Other classes can be non-public (default access), and they names do not need to match the file name.
6. Comments
- Use of comments: Comments can be added to improve code readability. Java supports three types of comments:
-
Single-line comment:
// This is a single-line comment -
Multi-line comment: ``` /*
- This is a multi-line comment */
-
Documentation comment: ``` /**
- This is a documentation comment */
-
7. Example Code
Here is an example of a Java source file that follows the above rules:
// This is an example class
package com.example; // package declaration
import java.util.List; // import statement
public class ExampleClass {
// class declaration
private String name; // instance variable
public ExampleClass(String name) {
// constructor
this.name = name;
}
public void display() {
// method
System.out.println("Name: " + name);
}
}
// Another class (non-public)
class Helper {
public void assist() {
System.out.println("Assisting...");
}
}