1. Introduction
In Java, package and import are two keywords that organize and access Java classes. A package is a namespace that organizes classes and interfaces by functionality and helps to avoid name clashes. The import statement is used to bring certain classes or the entire package into visibility, so you don't have to use the fully qualified name of a class, which includes its package.
2. Key Points
1. package defines a namespace under which classes are stored.
2. import is used to declare classes from other packages that are to be used in the code.
3. The package statement must be the first line in a Java source file (excluding comments).
4. The import statements must come after the package and before class declarations.
5. Using package, you can create a group of related classes, whereas import allows you to use classes from other packages.
3. Differences
package | import |
---|---|
Declares that a class belongs to a specific package. | Brings a specific class or an entire package into visibility. |
Organizes classes into namespaces to avoid name conflicts. | Avoids the need for fully qualified class names. |
Is declared once per file. | Can be used multiple times to import different classes or packages. |
4. Example
// File Name: com/example/util/Utility.java
package com.example.util;
public class Utility {
// utility methods
}
// File Name: com/example/main/MainClass.java
package com.example.main;
import com.example.util.Utility; // Importing a single class
public class MainClass {
public static void main(String[] args) {
// Since we imported Utility, we don't need to use com.example.util.Utility
Utility util = new Utility();
}
}
// Another way using a wildcard to import all classes in a package
// import com.example.util.*;
Output:
// No output in this case, these are just declarations and imports
Explanation:
1. In Utility.java, the package statement declares that Utility belongs to com.example.util.
2. In MainClass.java, import is used to bring Utility class from com.example.util into visibility.
3. Because of the import statement, you can instantiate Utility using its simple name rather than its fully qualified name.
5. When to use?
- Use the package keyword to organize your classes and control the namespace of your Java applications.
- Use the import keyword to access classes from different packages, making your code cleaner and easier to read.
Comments
Post a Comment
Leave Comment