为什么使用包 java.nio.file.Path 而不导入它?

问题描述

我有两个类:

public class ScriptTests {

    private final java.nio.file.Path test_file;
   // ...
}

public class TestD {
public static void main(String args[]) {
     java.nio.file.Path test_file= Paths.get(args[0]);
     // ....
}
}

那些类用于测试我编写的代码。我的问题是为什么他们总是用全名来使用这个包?为什么不简单地在开头使用 import,然后像在所有其他包中那样使用更简单的名称

例如:import java.io.*;

我问是因为它看起来很奇怪。我想可能是有原因的!

解决方法

当您需要使用不同包的两个类时,您可以使用类的整个声明,例如,如果您需要在一个方法中使用两个类 Date。如果您不需要使用两个或多个名称相同但包不同的类,那么最好使用导入来提高代码的可读性。

示例

package com.stackoverflow.question;

import java.sql.Timestamp;

public class Solution {
    public static void main(String args[]) {
        java.sql.Date sqlDate = new java.sql.Date(System.currentTimeMillis());
        java.util.Date utilDate = new java.util.Date();
        Timestamp timestamp = new Timestamp(System.currentTimeMillis());
        
        System.out.println(sqlDate);
        System.out.println(utilDate);
        System.out.println(timestamp);
    }
}

注意:导入一个特定包的所有类(“import java.sql.*”)是一种不好的做法,只需导入您需要的类.