Preventing instantiation of a class if argument to constructor is illegal?
<p>I have a public constructor which takes a parameter (int age) to create an object. I want to check if the passed parameter is legal or not, for example age cannot be negative. If its illegal, then don't create an object/instance. If legal, no problem.</p>

<p>I can only think of one way to do this - </p>

<p>Make constructor private. Create a static method with parameter (int age) to do all the checking and return a null if you pass it an illegal value. If you pass it a legal value, then create an object and return its reference.
Is there any other way of doing it ? Maybe from inside the constructor itself ?</p>

<p><strong>EDIT :</strong>
I thought of one problem with the above method. The factory method/object creator method can only be a static method for obvious reasons. What happens if the factory method has to access a member variable <em>(to do some checking)</em> to create an object ? Then, we will be forced to make that member variable static. This may not be okay in all cases. </p>

<p>Does it make sense ?</p>
