Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can a constructor NOT return a new instance?

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?

like image 546
user3501758 Avatar asked Feb 04 '26 20:02

user3501758


2 Answers

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");
} ...
like image 167
August Avatar answered Feb 07 '26 10:02

August


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.

like image 38
Sotirios Delimanolis Avatar answered Feb 07 '26 09:02

Sotirios Delimanolis



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!