Java 中可以有多少个同名公有类?


一个 Java 文件只包含一个具有特定名称的公有类。如果你创建一个具有相同名称的另一个类,它将成为一个重复类。但如果你尝试创建这样的类,编译器将生成一个编译时错误。

示例

public class Example {
}
public class Example{
   public void sample(){
      System.out.println("sample method of the Example class");
   }
   public void demo(){
      System.out.println("demo method of the Example class");
   }
   public static void main(String args[]){
      Example obj = new Example();
      obj.sample();
      obj.demo();
   }
}

错误

C:\Sample>javac Example.java
Example.java:6: error: duplicate class: Example
public class Example{
       ^
1 error

事实上,你不能在一个文件中创建两个公有类,只有一个类应该是公有类,并且它应该是类的名称。

如果你尝试在同一个文件中创建两个公有类,编译器会生成一个编译时错误。

示例

public class Sample {
}
public class Example{
   public void sample(){
      System.out.println("sample method of the Example class");
   }
   public void demo(){
      System.out.println("demo method of the Example class");
   }
   public static void main(String args[]){
      Example obj = new Example();
      obj.sample();
      obj.demo();
   }
}

错误

C:\Sample>javac Example.java
Example.java:2: error: class Sample is public, should be declared in a file named Sample.java
public class Sample {
       ^
1 error

更新于:2019 年 7 月 30 日

2K+ 浏览

开启你的 职业生涯

完成课程,获得认证

开始学习
广告
© . All rights reserved.