Tag Archives: Java

Does Java allow two classes in one file?

Short answer will be: no, it does not for public classes. But yes, it does for non-public ones.

According to JavaSE7 specification http://docs.oracle.com/javase/specs/jls/se7/html/jls-7.html#jls-7.6  it's up to compiler to allow or deny multiple public classes in one file:

If and only if packages are stored in a file system (§7.2), the host system may choose to enforce the restriction that it is a compile-time error if a type is not found in a file under a name composed of the type name plus an extension (such as .java or .jav) if either of the following is true:

  • The type is referred to by code in other compilation units of the package in which the type is declared.
  • The type is declared public (and therefore is potentially accessible from code in other packages).

In practise, all compilers I ever met applied this restriction. The rule is: one public class – one .java file (which is a compilation unit)  with the same name. 

For example, let's put two public classes in one file and we'll get compilation error:

Continue reading