public class A
{
}
public class B
{
public static void main(String[] args)
{
}
}
为什么我们不能将两个类都声明为公共(public)类?
为什么只有 Main
类可以公开?
我知道通过公开类,它可以让你在包中访问,但是如果我做
public class a
{
}
class B
{
public static void main(String[] args)
{
}
}
为什么这段代码报错
我们真的需要通知主类是公共(public)的吗因为每个类都是公共(public)的
因为一个 .java 文件只能包含一个公共(public)类。
如果您希望这两个类是公共(public)的,则必须将它们放入两个 .java 文件中:A.java
和 B.java
。
来自JLS 7.6. Top Level Type Declarations :
This restriction implies that there must be at most one such type per compilation unit. This restriction makes it easy for a Java compiler to find a named class within a package. In practice, many programmers choose to put each class or interface type in its own compilation unit, whether or not it is public or is referred to by code in other compilation units.