Why does Java not allow a top level class to be declared as private? Is there any other reason other than "We can't access a private class"?
Why does Java not allow a top level class to be declared as private? Is there any other reason other than "We can't access a private class"?
A top-level class as private would be completely useless because nothing would have access to it.
In theory, you could instantiate and call methods on a private top-level class (if such a thing were allowed by the language ... which it isn't!), but you would have to use reflection to do this. Sensibly (IMO) Sun decided that private top-level classes were not a good thing to support at the language level.
Actually, it is possible that the JVM might support top-level private "classes" created by bytecode magic. But it is not a useful thing to do.
UPDATE - In fact, the current JVM spec makes it clear that the ACC_PRIVATE bit of the access flags word for a class is "reserved for future use", and that Java implementations should treat it as unset. Thus, the above speculation is moot for any JVM that strictly implements the current specification.
As we already know, a field defined in a class using the private keyword can only be accessible within the same class and is not visible to the outside world.
So what will happen if we will define a class private? Will that class only be accessible within the entity in which it is defined which in our case is its package?
Let’s consider the below example of class A
package com.example;
class A {
private int a = 10;
// We can access a private field by creating object of same class inside the same class
// But really nobody creates an object of a class inside the same class
public void usePrivateField(){
A objA = new A();
System.out.println(objA.a);
}
}
Field ‘a’ is declared as private inside ‘A’ class and because of it, the ‘a’ field becomes private to class ‘A' and can only be accessed within ‘A’. Now let’s assume we are allowed to declare class ‘A’ as private, so in this case class ‘A’ will become private to package ‘com.example’ and will not be accessible from outside of the package.
So defining private access to the class will make it accessible inside the same package which the default keyword already does for us. Therefore there isn't any benefit of defining a class private; it will only make things ambiguous.
You can read more in my article Why an outer Java class can’t be private or protected.