-4

I was trying to write a Java program with more than 1 public class and it gave me the following error:

Class [classname] is public,should be declared in a separate file named 
[classname].java

Can't seem to find a convincing answer as to why this is happening.

Parth Mody
  • 75
  • 3
  • 8

3 Answers3

3

You can not declare more than one public class in one .java file. Separate your classes to different .java files.

Class1.java

public class Class1 {

}

Class2.java

public class Class2 {

}

This restriction implies that there must be at most one such type per compilation unit. This restriction makes it easy for a compiler for the Java programming language or an implementation of the Java virtual machine to find a named class within a package; for example, the source code for a public type wet.sprocket.Toad would be found in a file Toad.java in the directory wet/sprocket, and the corresponding object code would be found in the file Toad.class in the same directory.

Similar questions:

Community
  • 1
  • 1
bsiamionau
  • 8,099
  • 4
  • 46
  • 73
2

Every public class must be declared in it's own .java source file.

Davide Gualano
  • 12,813
  • 9
  • 44
  • 65
2

The class name is the same as the file name. If you have more than one class in a file, it creates a conflict which causes errors. So each class should be in a separate file with the file name same as the class name.

Aashray
  • 2,753
  • 16
  • 22