I need to create an object of some type. The class of the object has just one constructor (one that I've written).
My program receive requests to create instances of an objects with a parameter ID. I want to stop the constructor if the ID parameter contains a char that is not a digit.
I cannot check the parameter before, since I'm not the one who calls the constructor.
If you wish to exit a function early (including the constructor), you can simply use the return; command.
No, a constructor can't be made final. A final method cannot be overridden by any subclasses. As mentioned previously, the final modifier prevents a method from being modified in a subclass.
Note that the constructor name must match the class name, and it cannot have a return type (like void ). Also note that the constructor is called when the object is created. All classes have constructors by default: if you do not create a class constructor yourself, Java creates one for you.
Don't use init()/cleanup() members. If you have to call init() every time you create an instance, everything in init() should be in the constructor. The constructor is meant to put the instance into a consistent state which allows any public member to be called with a well-defined behavior.
Make the constructor private and expose a static factory method, that will validate and return a new instance of the object if the parameter is valid.
The only way to "stop" a constructor is to throw an exception. Bearing in mind of course that the caller is supposed to "know" about this exception and be able to handle the case where the constructor fails.
Throwing an exception from the constructor doesn't stop the object being created though, It just makes the assignment of its reference to a variable fail and the reference unavaliable (and therefore eligible for garbage collection) unless you make the mistake of passing this
to an external method from the constructor itself. (Which you shouldn't do anyway.)
How to solve this depends on what you want to happen when an illegal character is given, which in turn depends on what object we're talking about, and how the consuming library is using it.
The most reasonable thing to do would be to throw an IllegalArgumentException
, and this is what I'd suggest you do.
However, it might make sense to just return null
, too, even though I'd strongly recommend against it (you can't do this directly in the constructor, but you can create a factory method that does this).
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