Is there a legitimate use for non-nested classes in Java? For example:
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 under MyClass. NonNestedClass cannot access the fields of MyClass. Is there any difference, and more importantly, is there a legitimate use of this paradigm?
Is there any difference[?]
Yes.
A non-nested class, even if in the same file, is an independent, top-level class. It has no special relationship to the file's eponymous class.
Nested classes can access the members of the class in which they're nested, and vice-versa. (If the nested class is static, it needs an instance of the outer class to access the instance's fields.)
Nested classes can be accessed by name from other compilation units. But typically only the eponymous top-level class can be accessed by name from other compilation units.
And more importantly, is there a legitimate use of this paradigm?
It supports backwards compatibility with files written in Java 1.0, before nested classes were introduced in version 1.1. That was about 20 years ago now. This case doesn't come up very often.
Other than that, I've personally never found need of it. The typical pattern is to put a class and its auxiliary classes in a single file.
References
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With