Michael Brewer-Davis Michael Brewer-Davis - 14 days ago 5
Java Question

Java: Multiple class declarations in one file

In Java, you can define multiple top level classes in a single file, providing that at most one of these is public (see JLS ยง7.6). See below for example.


  1. Is there a tidy name for this technique (analogous to
    inner
    ,
    nested
    ,
    anonymous
    )?

  2. The JLS says the system may enforce the restriction that these secondary classes can't be
    referred to by code in other compilation units of the package
    , e.g., they can't be treated as package-private. Is that really something that changes between Java implementations?



e.g., PublicClass.java:

package com.example.multiple;

public class PublicClass {
PrivateImpl impl = new PrivateImpl();
}

class PrivateImpl {
int implementationData;
}

Answer

My suggested name for this technique (including multiple top-level classes in a single source file) would be "mess". Seriously, I don't think it's a good idea - I'd use a nested type in this situation instead. Then it's still easy to predict which source file it's in. I don't believe there's an official term for this approach though.

As for whether this actually changes between implementations - I highly doubt it, but if you avoid doing it in the first place, you'll never need to care :)

Comments