Create a null link

class A{

A(int i){
}
}

A obj=new A(1);

when creating an object, if I pass positive numbers, the object must be created. A obj = new A (-1); If the transmitted numbers are transmitted, the object should not be created.

How to apply a constructor for this

+5
source share
4 answers

If you do not want the object to be created, do not call new. A call newalways creates an object, even if it is then discarded due to an exception. If you just want the caller to not receive the object as a result of calling the constructor, you can make your constructor exclusive. If you want them to just get a null reference, you cannot do this in the constructor.

, new null:

public class A
{
    public static A createIfNonNegative(int i)
    {
        return i < 0 ? null : new A();
    }
}
+9
+3

Jon Skeet :

class A{

    A(int i){
        if(i<0) {
            throw new NumberBelowZeroException(i); // implementation of this exception is left as an exercise
        }
    }
}

A obj=new A(1);

, ( , , ), , .

+3

:

  • i, . , null:
    A a = createAInstance (i);
    if (a == null) {//- }
    else {// - }
    
    therefore, depending on the algorithm, you can check the state at the level where you are using A a:
    if (i> = 0) {A a = new A (i); // do something}
    else {// do something else}
    
  • The logic is implemented only in A: use a Null Object to implement a null stub for A, and the code related to the instance of A should not feel the difference;
  • the logic is mixed: use a Null Object as in 2.
0
source

All Articles