We can restrict the creation of object of a class by making its constructor private. But this constructor could still be called from within the class. Is there any way to prevent this in Java?
Thanks.
You cannot access a private constructor from any other class. If the object is yet not initialised, then you can write a public function to call the private instructor. If the object is already initialised, then you can only return the instance of that object.
Yes, we can declare a constructor as private. If we declare a constructor as private we are not able to create an object of a class. We can use this private constructor in the Singleton Design Pattern.
1) NO! A constructor belongs to the class in which it is declared. A sub class is a different class and must have its own constructor. So, constructors simply can't be overridden.
The only way to "stop" a constructor is to throw an exception.
No, there is no clean way to do this. And really I cannot see a reason to do so. Because if the constructor is private, this means that he can only be called from code within this exact class (no subclasses, or other classes in the package), so if you do not want the constructor to be called, put a comment on it which says so.
Since everyone who is able to use the constructor would be able to remove any measures you put there to prevent the calling of the constructor, it would have no real effect.
Besides, if you need a singleton, then you may want the constructor to be run at least once (except if your idea of a singleton is a purely static 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