6

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?

Andy Thomas
  • 84,978
  • 11
  • 107
  • 151
Steven Solomon
  • 301
  • 1
  • 3
  • 14
  • that's not valid syntax. you must have a class at the top level. – Jeffrey Blattman Jul 10 '15 at 17:42
  • 2
    @JeffreyBlattman surprisingly, it is valid - MyClass.java declares a top level public class "MyClass". The spec doesn't say you can't have *another* top level class in the same file. This confused the hell out of me earlier in my career when I saw the second class appear in the generated Javadoc but couldn't find a separate file for it in the source. – Thorn G Jul 10 '15 at 17:43
  • possible duplicate of [Java: Multiple class declarations in one file](http://stackoverflow.com/questions/2336692/java-multiple-class-declarations-in-one-file) – Chetan Kinger Jul 10 '15 at 17:54
  • It's a good question, as far as I know, no! but I don't know why we can do that. – David Pérez Cabrera Jul 10 '15 at 17:54
  • @CKing - This does not look like a duplicate of that question, which asks for a name and whether this optional constraint is typically enforced. This question asks for differences from static nested classes, and whether there's a use case. – Andy Thomas Jul 10 '15 at 18:27
  • @TomG yes you are right. it can't be public however. – Jeffrey Blattman Jul 10 '15 at 21:36

2 Answers2

3

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

Andy Thomas
  • 84,978
  • 11
  • 107
  • 151
0

I often use it in test code, it helps to be able to keep everything in a single file, but I don't know if that qualifies as a valid use case.

Miserable Variable
  • 28,432
  • 15
  • 72
  • 133