I was reading the Java documentation here and this is what I found:
You can also add modifiers like public or private at the very beginning—so you can see that the opening line of a class declaration can become quite complicated. The modifiers public and private, which determine what other classes can access
MyClass
, are discussed later in this lesson.
It specifies that I can create a class with the private
or public
modifiers. However, when I try to use the private
modifier, I get an error that it is an illegal modifier for that class band: only public
, abstract
and final
are permitted.
I understand that the private
modifier is not useful, but why does this tutorial, which is from the official Java site, state that I can create a class using it? Did I miss something?
Top level classes cannot be private
. However, nested classes can be private
.
See JLS
The access modifier public (§6.6) pertains only to top level classes (§7.6) and to member classes (§8.5), not to local classes (§14.3) or anonymous classes (§15.9.5).
The access modifiers protected and private (§6.6) pertain only to member classes within a directly enclosing class or enum declaration (§8.5).
You cannot have a private
top level class. You can have a private
inner or nested class.
Obviously a private
top level class would be somewhat useless as you would not be allowed to access it from anywhere.
So this is allowed
public class MyClass {
private class MyInnerClass {
}
}
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