我可以在一个Java包中定义多个公共类吗?


不可以。在一个Java文件中定义多个类时,需要确保其中只有一个类是公共的。如果在一个文件中有多个公共类,则会产生编译时错误。

示例

在下面的示例中,我们有两个类Student和AccessData,它们都在同一个文件中,并且都被声明为公共的。

 在线演示

import java.util.Scanner;
public class Student {
   private String name;
   private int age;
   Student(){
      this.name = "Rama";
      this.age = 29;
   }
   Student(String name, int age){
      this.name = name;
      this.age = age;
   }
   public void display() {
      System.out.println("name: "+this.name);
      System.out.println("age: "+this.age);
   }
}
public class AccessData{
   public static void main(String args[]) {
      //Reading values from user
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter the name of the student: ");
      String name = sc.nextLine();
      System.out.println("Enter the age of the student: ");
      int age = sc.nextInt();
      Student obj1 = new Student(name, age);
      obj1.display();
      Student obj2 = new Student();
      obj2.display();
   }
}

编译时错误

编译上述程序时,会产生以下编译时错误。

AccessData.java:2: error: class Student is public, should be declared in a file named Student.java
public class Student {
       ^
1 error

要解决此问题,您需要将其中一个类移到单独的文件中,或者:

  • 删除不包含`public static void main(String args)`方法的类之前的public声明。

  • 使用包含main方法的类名命名文件。

在本例中,请删除Student类之前的public。将文件命名为“AccessData.java”。

更新于:2019年9月10日

6K+ 次浏览

启动您的职业生涯

完成课程获得认证

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