Use case for multiple top-level Java classes in a single file?

Is there legal use for non-nested classes in Java? For instance:

MyClass.java: final class NonNestedClass { ... } public class MyClass { private NonNestedClass nonNested; ... } 

As far as I can tell, this is equivalent to having a static nested class in MyClass. NonNestedClass cannot access MyClass fields. Is there any difference, and more importantly, is there a legitimate use of this paradigm?

+5
source share
2 answers

Is there a difference [?]

Yes.

A non-nested class, even if in the same file, is an independent top-level class. It has no special relation to the file class of the same name.

Nested classes can access members of the class in which they are nested, and vice versa. (If the nested class is static, it needs an instance of the outer class to access the instance fields.)

Nested classes can be accessed by name from other compilation units. But usually only the top-level class of the same name can be obtained by name from other compilation units.

And more importantly, is there a legitimate use of this paradigm?

It supports backward compatibility with files written in Java 1.0 before nested classes were introduced in version 1.1. That was about 20 years ago. This case does not occur very often.

Other than that, I personally never found a need for it. A typical template is to put a class and its helper classes in a single file.

References

+3
source

I often use it in test code, it helps to save everything in one file, but I do not know if this corresponds to the correct use case.

0
source

All Articles