Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is the "Declaring Classes" Java tutorial wrong about private classes?

Tags:

java

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?

like image 529
pagas Avatar asked Dec 01 '22 03:12

pagas


2 Answers

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).

like image 136
zw324 Avatar answered Dec 05 '22 11:12

zw324


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 {
    }
}
like image 42
Boris the Spider Avatar answered Dec 05 '22 11:12

Boris the Spider