Java 如果我没有指定,我的类所在的默认包是什么?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2335211/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
What is the default package in which my classes are put if I don't specify it?
提问by devoured elysium
Let's assume I have a file named Main.java with the following code:
假设我有一个名为 Main.java 的文件,其中包含以下代码:
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
谢谢
采纳答案by Lachlan Roche
A class that is not in a named package is in an unnamed package. Thus the full class name is Main
.
不在命名包中的类在未命名包中。因此完整的类名是Main
.
Such classes cannot be usedfrom a named package, except via reflection.
这样的类不能使用来自名为包,除了通过反射。
The JLS says that:
JLS 说:
Unnamed packages are provided by the Java SE platform principally for convenience when developing small or temporary applications or when just beginning development.
Java SE 平台提供未命名包主要是为了在开发小型或临时应用程序或刚开始开发时提供便利。
回答by Michael Borgwardt
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.
Java 没有命名空间,它有包。是的,没有包声明的类隐含地属于“未命名包”,通常也称为“默认包”。但是,由于无法从未命名包中导入类,并且语言规范明确允许实现对未命名包中的类是否以及如何彼此可见具有不同的规则,因此通常将所有类放入已命名的包中是一个好主意包除了实验代码。