What is the default package in which my classes are put if I don't specify it?

孤街浪徒 提交于 2019-11-26 08:27:23

问题


Let\'s assume I have a file named Main.java with the following code:

public class Main {
    public static void main(String[] args) {
        System.out.println(\"Hello world\");
    }
}

Is it put in a specific package, in (maybe?) an unnamed package?

Thanks


回答1:


A class that is not in a named package is in an unnamed package. Thus the full class name is Main.

Such classes cannot be used from a named package, except via reflection.

The JLS says that:

Unnamed packages are provided by the Java SE platform principally for convenience when developing small or temporary applications or when just beginning development.




回答2:


Java does not have namespaces, it has packages. And yes, classes with no package declarations are implicitly part of an "unnamed package", often also called "default package". However, since it's not possible to import classes from an unnamed package and since the language spec explicitly allows implementations to have different rules about whether and how classes in unnamed packages are visible to each other, it's generally a good idea to put all classes in named packages except for experimental code.




回答3:


According to the JLS it's called:

7.4.2 Unnamed Packages

A compilation unit that has no package declaration is part of an unnamed package.



来源:https://stackoverflow.com/questions/2335211/what-is-the-default-package-in-which-my-classes-are-put-if-i-dont-specify-it

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