0

Does it creates individual .class files when it gets compiled? Is it something right to do?

Fuheybady
  • 1
  • 1
  • 3
    That would be easy to try out! – Henry Feb 16 '21 at 14:02
  • You can create inner classes and anonymous classes inside of a main public class. I do it all the time so I can paste [answers in Stack Overflow](https://stackoverflow.com/questions/66210678/swing-window-doesnt-return-value-after-x-time/66212769#66212769) as one block of code. – Gilbert Le Blanc Feb 16 '21 at 14:23
  • Try it and you’ll see multiple.class files resulting after compile. Problem is it’s non-standard, non-idiomatic practice, thus confusing. – Woodchuck Feb 16 '21 at 14:25
  • @GilbertLeBlanc You can even define multiple top-level classes in a single file, but only one of them can be public. – Mark Rotteveel Feb 16 '21 at 14:42

1 Answers1

1

The Java Language Specification (JLS 7.6) states:

"It is a compile-time error if the name of a top level type appears as the name of any other top level class or interface type declared in the same package."

Since all top level type declarations in a file are members of the same package, it follows that if you declare two top-level types with the same name in the same file, then the second one is violating the above rule.

The spec also states the following:

"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 ordinary 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)."

This means that (for such implementations) only one of the top-level types in a file can be public.

(Most Java compilers do enforce this restriction.)

However, if you don't break the restrictions above, the Java language allows you to declare multiple top level types in a single file.


Does it create individual .class files when it gets compiled?

Yes. Indeed, there is also a separate .class file generated for any nested or inner classes, and for any lambdas.


Is it something right to do?

It is generally thought to be a bad idea to do this. Some Java style guides explicitly say there should be one top-level type declaration per source file. Others are silent on this.

Since multiple types in a single source file are unusual in practice, most programmers don't expect this. Thus it is a readability concern, which is a practical reason not to do it.

Stephen C
  • 698,415
  • 94
  • 811
  • 1,216