Is there any actual difference between this
public class OuterClass {
private class InnerClass {
public InnerClass() {}
}
}
and this?
public class OuterClass {
private class InnerClass {
private InnerClass() {}
}
}
There is no rule that constructor to be public . Generally we define it public just because we would like to instantiate it from other classes too . Private constructor means,"i dont let anyone create my instance except me ". So normally you would do this when you like to have a singleton pattern.
The private class can't be extended by classes outside of the package, so protected has no use either. Even when using reflections, a public constructor is not accessible by default from other packages and will throw a IllegalAccessException . It checks the class visibility first, then the member visibility.
Unlike a class, an inner class can be private and once you declare an inner class private, it cannot be accessed from an object outside the class. Following is the program to create an inner class and access it.
Modifiers public, protected and, private are allowed with constructors. We can use a private constructor in a Java while creating a singleton class. The Singleton's purpose is to control object creation, limiting the number of objects to only one.
Accessing private members from another class is slightly more complicated because the JVM doesn't actually allow this. As a result the compiler injects accessor methods which makes it slightly slower or your stack trace more complicated.
For these reason I leave it as package local.
BTW The constructor of an abstract class
doesn't need to be public
either. It may as well be protected
or package local
private static class A {
private A() {
throw new Error();
}
}
public static void main(String... ignored) {
new A();
}
prints an extra stack trace element.
Exception in thread "main" java.lang.Error
at Main$A.<init>(Main.java:8)
at Main$A.<init>(Main.java:6)
at Main.main(Main.java:12)
Make the constructor package local and the second one disappears.
As far as other classes are concerned, it shouldn't since the inner class is declared as private. They can't see it at all.
It shouldn't make a difference to the enclosing class since it contains the inner class.
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