Is it possible to have a constructor decide, based on the argument, not to make a new instance? For example:
public class Foo{
public Foo(int n){
if(n<0){
//DO NOT make this
}
else{
//Go ahead and make this instance
}
}
}
I know it is not possible to do this:
public class Foo{
public Foo(int n){
if(n<0){
//DO NOT make this
this = null;
}
else{
//Go ahead and make this instance
}
}
}
Is there a way to do the same thing correctly?
A constructor has no control over what will be returned. However, you can use static factory methods for more flexibility:
public static Foo newInstance(int n) {
if (n < 0) {
return null;
} else {
return new Foo(n);
}
}
It's better to throw an exception than return null when an invalid number is supplied:
if (n < 0) {
throw new IllegalArgumentException("Expected non-negative number");
} ...
A constructor does not return an instance. The new operator (as part of the instance creation expression) creates the instance and the constructor initializes it. Once you've understood that, you realize you can't do what you are suggesting.
Your calling code should decide if it creates an instance or not, not the constructor.
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