Can I define more than one public class in a Java package?


No, while defining multiple classes in a single Java file you need to make sure that only one class among them is public. If you have more than one public classes a single file a compile-time error will be generated.

Example

In the following example we have two classes Student and AccessData we are having both of them in the same class and declared both public.

 Live Demo

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();
   }
}

Compile-time error

On compiling, the above program generates the following compile-time error.

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

To resolve this either you need to shift one of the classes into a separate file or,

  • Remove the public declaration before the class that doesn’t contain a public static void main(String args) method.

  • Name the file with the class name that contains main method.

In this case, remove the public before the Student class. Name the file as “AccessData.java”.

raja
Published on 10-Sep-2019 16:15:18
Advertisements