There is a statement in the book I'm reading for the SCJP qualification, it says :
Files with no public classes have no naming restrictions
That has made me ask, why would you ever want to do this?
If there are no public classes, then how could other classes ever import and use the file? The only purpose I can see is if the file runs standalone in itself, which could also be odd, such as have an entire application in one file
If a top level class or interface type is not declared public, then it may be accessed only from within the package in which it is declared.
The actual requirement is slightly different: every Java public class must be in a compilation unit with the name PublicClassName. java . But it's perfectly fine to have a compilation unit that does not contain a public class.
Each Java source file contains a single public class or interface. When private classes and interfaces are associated with a public class, you can put them in the same source file as the public class. The public class should be the first class or interface in the file.
public is a Java keyword which declares a member's access as public. Public members are visible to all other classes. This means that any other class can access a public field or method. Further, other classes can modify public fields unless the field is declared as final .
This is valid for package-private classes as well. And you can use package-private classes within the same package. (And in that case you don't have to import it, because it's in the same package.)
For example, the JapaneseImperialCalendar
class is package-private, because it is only used from Calendar.createCalendar(..)
- it is not part of the public API. You can't directly instantiate the japanese calendar, but you can still use it by its interface. Same goes for all unmodifiable collections that are obtained by methods like Collections.unmodifiableList(..)
- they are package-private.
So the .java
file of JapaneseImperialCalendar
could've been arbitrary. However, it is advisable not to diverge from the established practice of naming even package-private files after the class name.
You can create a file named package-info.java
, which contains only a package
statement. The javadoc 1.5+ tool treats a javadoc comment on this package statement exactly like a package.html
file. In addition, you can add package-level annotations such as @Generated
to this statement, which you can't do in package.html
.
Because package-info
is not a valid Java identifier, there is no risk of this file ever clashing with an existing Java class (i.e. backwards compatibility).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With