Why only 1 public class in Java file

In any Java file, why can we have only one public class whose name is same as the Java file name?


Solution 1:

It forces all Java code to be organized in a certain way, which in the long run helps improve code readability.

The Java designers chose a strict approach that enforces their idea of good design practices, and this is part of that theme. Contrast that with the anything-goes attitude in Perl.

Solution 2:

According to this source, it is for efficient compilation :

In the sidebar it explains why: "This restriction is not yet enforced by the compiler, although it's necessary for efficient package importation"

It's pretty obvious - like most things are once you know the design reasons - the compiler would have to make an additional pass through all the compilation units (.java files) to figure out what classes were where, and that would make the compilation even slower.

The same applies also for imports of source files in IDEs. Another reason would be reasonable source sizes.

Solution 3:

These are the rules. Although it is not quite true. You can define internal classes inside you "main" class like this:

public class A {  
   public class B {  
       ...  
   }  
}