我可以在一個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.