我正在读一本 Java 书,并看到以下段落:
import and package statements apply to all classes within a source code file. In other words, there's no way to declare multiple classes in a file and have them in different packages or use different imports.
我很难理解这一段,请问有人可以解释一下它背后的想法吗?
最佳答案
您可以在单个文件中声明多个类,例如以下将定义类 Foo
, Bar
和Baz
:
package com.example;
import java.util.List;
import java.util.ArrayList;
public class Foo {
public class Bar {}
}
class Baz {}
每个文件只能有一个顶级公共(public)类,在本例中 Foo
.
注意包声明;这适用于文件中的所有类;所有类(class)都在 ' com.example
中' 命名空间 - 你不能有 Foo
在'com.example
' 和 Bar
在'com.example.something
'
导入适用于该文件中的所有类;您不能仅将导入提供给 Baz
(或文件中声明的类的任何子集)
您可能想知道什么 Bar
正在做Foo
内声明的事情类(class);这是一个内部类 - 关于内部类的(有点稀疏)oracle 教程是 here
关于java - import 和 package 语句适用于源代码文件中的所有类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31817726/