More Than One Package in Statement?
No, you cannot have more than one package statement in a single Java source file. A source file can belong to only one package, and this package is specified by a single package statement at the very beginning of the file. Any attempt to include multiple package statements in one source file will result in a compilation error.
Table of Contents
Key Points
- 1. Single Package Declaration: Only one package statement is allowed per source file, and it must be the first line of code (excluding comments and blank lines).
- 2. Organizing Classes: To have classes in different packages, you need to create separate source files for each package.
- 3. Imports: You can import classes from multiple packages within a single source file.
```java
// This is incorrect and will cause a compilation error
package com.example.myapp;
package com.example.utils;
public class MyClass {
// Class definition
}
```
// Correct way with a single package statement
package com.example.myapp;
public class MyClass {
// Class definition
}
```
Organizing Multiple Packages
If you need to organize your classes into multiple packages, you should create separate source files for each package.
```
src/
├── com/
│ ├── example/
│ │ ├── myapp/
│ │ │ └── MyClass.java
│ │ └── utils/
│ │ └── Utility.java
```
**MyClass.java**:
```java
package com.example.myapp;
import com.example.utils.Utility;
public class MyClass {
public static void main(String[] args) {
Utility.printMessage("Hello from Utility!");
}
}
```
```java
package com.example.utils;
public class Utility {
public static void printMessage(String message) {
System.out.println(message);
}
}
```
Explanation
1. MyClass.java:
- This file declares the package `com.example.myapp` and imports the `Utility` class from `com.example.utils`.
- The `main` method uses the `Utility` class.
2. Utility.java:
- This file declares the package `com.example.utils`.
By organizing your code this way, you maintain a clear and logical structure, with each source file belonging to exactly one package.
Summary
In Java, a source file can have only one package statement, which must be the first line of code (excluding comments and blank lines). To work with multiple packages, you must use separate source files for each package. This ensures a clear organizational structure and prevents compilation errors related to multiple package declarations.