杰瑞科技汇

java import class

Of course! Let's break down the import statement in Java, which is fundamental for organizing and reusing code.

java import class-图1
(图片来源网络,侵删)

What is the import Statement?

In simple terms, the import statement in Java is a way to tell the compiler which classes you want to use from other packages.

  • Analogy: Think of your Java project as a large building. The classes you write are like rooms in your apartment. Other people's code (like Java's built-in libraries) is like a public library across the street. The import statement is like writing down the address of a specific book (class) from that library so you can easily reference it in your apartment.

Why Do We Need It?

Java organizes its classes into packages. A package is essentially a folder or namespace that groups related classes together to avoid name conflicts and organize the codebase.

For example:

  • All classes for handling user input/output are in the java.io package.
  • All classes for creating graphical user interfaces (GUIs) are in the java.awt package.
  • All utility classes like ArrayList and Date are in the java.util package.

If you want to use a class that's not in the same package as your current class, you need to import it.

java import class-图2
(图片来源网络,侵删)

The Two Forms of import

There are two main ways to use the import statement.

Importing a Specific Class

This is the most common and recommended practice. You import only the single class you need.

Syntax:

import packageName.ClassName;

Example: Let's say you want to use the ArrayList class, which is in the java.util package.

java import class-图3
(图片来源网络,侵删)
// File: MyProgram.java
// Import the ArrayList class specifically
import java.util.ArrayList;
public class MyProgram {
    public static void main(String[] args) {
        // Now you can use ArrayList directly without the full package name
        ArrayList<String> names = new ArrayList<>();
        names.add("Alice");
        names.add("Bob");
        System.out.println("Names: " + names);
    }
}

Without the import statement, you would have to write the full class name every time, which is verbose:

// Without import
public class MyProgram {
    public static void main(String[] args) {
        // You must use the fully qualified name
        java.util.ArrayList<String> names = new java.util.ArrayList<>();
        names.add("Alice");
        names.add("Bob");
        System.out.println("Names: " + names);
    }
}

As you can see, import java.util.ArrayList; makes the code much cleaner and easier to read.

Importing All Classes from a Package (Wildcard Import)

You can use a wildcard () to import all public classes from a specific package.

Syntax:

import packageName.*;

Example:

// Import ALL classes from the java.util package
import java.util.*;
public class MyProgram {
    public static void main(String[] args) {
        // You can now use ArrayList, HashMap, Date, etc. from java.util
        ArrayList<String> names = new ArrayList<>();
        names.add("Charlie");
        java.util.Date today = new java.util.Date(); // You can still use the full name if there's a conflict
        System.out.println("Names: " + names);
        System.out.println("Today's date: " + today);
    }
}

Important Note on Wildcard Imports:

  • It does NOT import sub-packages. import java.util.*; imports classes from java.util but not from java.util.stream or java.time. You must import those separately.
  • It's generally considered good practice to import specific classes rather than using wildcards. It makes your dependencies explicit and helps other developers (and your future self) understand exactly which classes your file relies on. However, for tests or small utility classes, wildcard imports are common and acceptable.

The Special Case: java.lang

You might have noticed that you never have to import basic classes like String, System, Integer, or Object.

// We don't need to import String or System!
public class HelloWorld {
    public static void main(String[] args) {
        System.out.println("Hello, " + "World!");
    }
}

This is because the java.lang package is implicitly imported by the Java compiler for every single class. It contains the most fundamental and core Java classes that are essential for the language to work.


Static Imports (A Special Case)

There's also a static import which allows you to import static members (fields and methods) of a class so you can use them without the class name.

Syntax:

import static packageName.ClassName.staticMember;

Example: The Math class has many useful static methods like sqrt() and pow().

// Without static import
public class MyMath {
    public static void main(String[] args) {
        double root = Math.sqrt(16); // Must use Math.
        double power = Math.pow(2, 3);
        System.out.println("Square root of 16 is: " + root);
        System.out.println("2 to the power of 3 is: " + power);
    }
}

With a static import, you can make the code cleaner:

// Import the static methods directly
import static java.lang.Math.sqrt;
import static java.lang.Math.pow;
public class MyMathClean {
    public static void main(String[] args) {
        // No need to write Math.sqrt or Math.pow
        double root = sqrt(16);
        double power = pow(2, 3);
        System.out.println("Square root of 16 is: " + root);
        System.out.println("2 to the power of 3 is: " + power);
    }
}

Static imports should be used sparingly. They are best for utility classes like Math or Collections where you use a few static members frequently. Overusing them can lead to code that is hard to read, as it's not immediately clear where a method comes from.


Best Practices Summary

  1. Be Specific: Prefer import java.util.ArrayList; over import java.util.*;.
  2. Keep it Organized: Group your imports logically (e.g., standard library imports first, then third-party library imports, then your own project imports).
  3. Avoid Static Imports for Clarity: Only use static imports for truly ubiquitous and static utility methods. Avoid them for static constants unless they are used extremely frequently.
  4. Don't Import java.lang: It's automatic, so don't write import java.lang.String;. It will compile but is redundant.
分享:
扫描分享到社交APP
上一篇
下一篇