Search code examples
javaclassprivateaccess-modifiers

Why cannot I use a package-private (implicit) class as the top-level class of a java file?


I am new to Java. Maybe the question is a bit naive.

For example, I have a pkg1, in which there are 2 Java files: f1.java and f2.java

As the title, I feel it is reasonable to use a package-private-top-level class for f1, then use a public-top-level class for f2, then the outside of pkg1 can still access f1 via f2.

I can even have f3, f4... ..., which are all using package-private class as their top-level class. Then f2.java will become a package-interface file for the rest of files in pkg1.

So, why is the fact that a top-level class must be public? Just to prevent from unnecessary complexity?


Solution

  • According to Oracle Java tutorial, public isn't the only possible modifier for top-level class:

    A class may be declared with the modifier public, in which case that class is visible to all classes everywhere. If a class has no modifier (the default, also known as package-private), it is visible only within its own package

    So, basically, there's no problem in making some classes protected or package-private if your design requests it.

    Term 'top-level class' actually exists in Java as well as terms 'inner class' and 'nested class', I suggest you to take a look on this page to clear some basics of java class hierarchy.