I am new to Java. I want to know what it is the use of public constructor in a private class. Private class inside the class can be initialized from the same class then what it is the use to make the constructor of private class to public?
public class MainActivity extends Activity { private class AcceptThread extends Thread { public AcceptThread() { } } }
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.
A private constructor is a special instance constructor. It is generally used in classes that contain static members only. If a class has one or more private constructors and no public constructors, other classes (except nested classes) cannot create instances of this class.
No, Constructors can be public , private , protected or default (no access modifier at all). Making something private doesn't mean nobody can access it. It just means that nobody outside the class can access it. So private constructor is useful too.
Access specifiers/modifiers allowed with constructorsModifiers public, protected and, private are allowed with constructors. We can use a private constructor in a Java while creating a singleton class.
There doesn't seems to be any real use case for public or protected modifiers with private classes. If you have multiple classes in a single file though (but not nested or local), you need non-private constructors to instantiate the private classes.
// X.java public class X { private Y y = new Y(); } class Y { Y () { // if this were private, X wouldn't be able to create an instance of Y } }
Actually default or protected
visibility would be enough to create an instance in this case. All non-private modifiers allow you to create instances from other classes within the same package but practically have the same visibility.
public
methods have no use here.protected
has no use either.IllegalAccessException
. It checks the class visibility first, then the member visibility.The default modifier is the most restrictive modifier that allows you to directly call the constructor from other classes, so package-private seems to be the most appropriate visibility for the constructor and also any other non-private methods. This also has the advantage that if you change the class visibility in the future, you don't accidentally expose the constructor or any methods to the public.
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