Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Java by (3.9k points)

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;

}

1 Answer

0 votes
by (46k points)
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.

Related questions

0 votes
1 answer
asked Dec 2, 2019 in Java by Anvi (10.2k points)
0 votes
1 answer
asked Nov 25, 2019 in Java by Anvi (10.2k points)
0 votes
1 answer

Browse Categories

...