How I can I return a
null
value from an object constructor?
The simple answer is : no, you can't.
The explanation why is simple. You don't return any value whatsoever from an
object constructor. The object has already been created - in the constructor
you're just initializing the object's state. So there isn't any way to return a
null
value.
However, if you want to throw a spanner in the works, and stop someone using
your object (which is usually the intent of returning a null value, or to
indicate an error), why not throw a NullPointerException
?
public MyClass() { // Something might go wrong, so throw a null pointer exception throw new NullPointerException() ; }