What Java classes/packages are automatically imported? [duplicate]

允我心安 提交于 2020-12-08 06:37:27

问题


class HelloWorld {
    public static void main(String[] args) {
        System.out.println("Hello, World!"); 
    }
}

In the above example we are using the println method without importing the package of it. So I want to know: What are the packages or classes included automatically?


回答1:


Everything in java.lang is imported by default - here you are using java.lang.System and java.lang.String




回答2:


There are two packages imported by default:

  • java.lang
  • The package in which the current class is located (in the case of the above code, this is ostensibly the default package, from which you can't otherwise import explicitly).

From the language spec:

Code in a compilation unit automatically has access to all types declared in its package and also automatically imports all of the public types declared in the predefined package java.lang.

So, you only have access to public types in java.lang, but you have access to all top-level types in the current package.

But it's important to note that Java packages aren't hierarchical, despite the appearance, so this means that e.g. java.lang.reflect is not also imported automatically because of java.lang being imported.




回答3:


In every java class, java.lang is imported by default.

Apart from this, package (namely non-private classes of the package) you're having your class in, is also available/visible to your class, unless you have your class in a default package, which is if you have your class without package definition.



来源:https://stackoverflow.com/questions/53852375/what-java-classes-packages-are-automatically-imported

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!