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

Java 8Object Oriented ProgrammingProgramming

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.


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(){ = "Rama";
      this.age = 29;
   Student(String name, int age){ = name;
      this.age = age;
   public void display() {
      System.out.println("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.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);
      Student obj2 = new Student();

Compile-time error

On compiling, the above program generates the following compile-time error. error: class Student is public, should be declared in a file named
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 “”.

Published on 10-Sep-2019 12:45:18