Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Preventing call of a private constructor from within the class in Java

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.

like image 404
code_pro Avatar asked May 23 '10 19:05

code_pro


People also ask

How do you call a private constructor from a different class?

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.

Can we call private constructor in Java?

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.

Can we override private constructor in Java?

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.

How do you stop a constructor in Java?

The only way to "stop" a constructor is to throw an exception.


1 Answers

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).

like image 197
Alfonso Avatar answered Oct 26 '22 22:10

Alfonso