Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

nested

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?

like image 316
Steven Solomon Avatar asked Oct 19 '22 07:10

Steven Solomon


1 Answers

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

  • Nested classes introduced in version 1.1 -- The best reference I could find still accessible online is this copy of Appendix D of "The Java Programming Language."
  • The optional constraint on multiple top-level type declarations in a single file -- Java Language Specification, Section 7.6: "Top Level Type Declarations".
  • Accessibility of private members of top-level class and its nested auxiliary classes - Java Language Specification, Section 6.6.1: Determining Accessibility".
like image 120
Andy Thomas Avatar answered Nov 05 '22 07:11

Andy Thomas