为什么在实例上调用方法时不需要import类的引用(Java) [英] Why is import of class not needed when calling method on instance (Java)

查看:294
本文介绍了为什么在实例上调用方法时不需要import类的引用(Java)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

令我困惑的例子:

Thing.java:

Thing.java:

import java.util.Date; 

class Thing { 
    static Date getDate() {return new Date();}
}

(同一包)TestUsesThing.java:

(same package) 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
    }

}

为什么不需要导入Date以便能够在其中一个上调用getTime()?

Why is it not necessary to import Date to be able to call getTime() on one of them?

推荐答案

Java只是必要的,所以如果您键入

Importing in Java is only necessary so the compiler knows what a Date is if you type

Date date = new Date();

导入不像C中的 #include / C ++;类路径上的所有类型都是可用的,但您 import 只是为了不必写完全限定名称。在这种情况下,这是不必要的。

Importing is not like #include in C/C++; all types on the classpath are available, but you import them just to keep from having to write the fully qualified name. And in this case, it's unnecessary.

这篇关于为什么在实例上调用方法时不需要import类的引用(Java)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆