Possible Duplicate:
Java: Why can we define a top level class as private?
Why can't we declare a private outer class? If we can have inner private class then why can't we have outer private class...?
Possible Duplicate:
Java: Why can we define a top level class as private?
Why can't we declare a private outer class? If we can have inner private class then why can't we have outer private class...?
Private outer class would be useless as nothing can access it.
See more details:
Java: Why can we define a top level class as private?
To answer your question:
If we can have inner private class then why can't we have outer private class...?
You can, the distinction is that the inner class is at the "class" access level, whereas the "outer" class is at the "package" access level. From the Oracle Tutorials:
If a class has no modifier (the default, also known as package-private), it is visible only within its own package (packages are named groups of related classes — you will learn about them in a later lesson.)
Thus, package-private (declaring no modifier) is the effect you would expect from declaring an "outer" class private, the syntax is just different.
private
modifier will make your class inaccessible from outside, so there wouldn't be any advantage of this and I think that is why it is illegal and only public
, abstract
& final
are permitted.
Note : Even you can not make it protected
.
You can.
package test;
public class Test {
public static void main(String[] args) {
B b = new B();
}
}
class B {
// Essentially package-private - cannot be accessed anywhere else but inside the `test` package
}
You can't have private
class but you can have second
class:
public class App14692708 {
public static void main(String[] args) {
PC pc = new PC();
System.out.println(pc);
}
}
class PC {
@Override
public String toString() {
return "I am PC instance " + super.toString();
}
}
Also remember that static
inner class is indistinguishable of separate class except it's name is OuterClass.InnerClass
. So if you don't want to use "closures", use static inner class.
private makes the class accessible only to the class in which it is declared. If we make entire class private no one from outside can access the class and makes it useless.
Inner class can be made private because the outer class can access inner class where as it is not the case with if you make outer class private.