为什么在实例上调用方法时不需要导入类(Java)

jju*_*uma 13 java compiler-construction

让我感到困惑的一件事 - 一个例子:

Thing.java:

import java.util.Date; 

class Thing { 
    static Date getDate() {return new Date();}
}
Run Code Online (Sandbox Code Playgroud)

(相同的包)TestUsesThing.java:

// not importing Date here.

public class TestUsesThing {

    public static void main(String[] args) {
        System.out.println(Thing.getDate().getTime()); // okay
        // Date date = new Date(); // naturally this wouldn't be okay
    }

}
Run Code Online (Sandbox Code Playgroud)

为什么没有必要导入Date才能在其中一个上调用getTime()?

Mic*_*ers 26

只需要在Java中导入,因此编译器知道Date如果键入是什么

Date date = new Date();
Run Code Online (Sandbox Code Playgroud)

导入与#includeC/C++不同; 类路径上的所有类型都可用,但您import只需要编写完全限定名称即可.在这种情况下,这是不必要的.