Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating null reference

Tags:

java

class A{

A(int i){
}
}

A obj=new A(1);

while creating Object if i pass positive numbers object must be created. A obj=new A(-1); If negetive numbers are passed it object must not be created.

How to adjsut the constructor to do this

like image 210
user492052 Avatar asked Nov 04 '10 08:11

user492052


1 Answers

If you don't want an object to be created, don't call new. Calling new always creates an object, even if it then gets thrown away due to an exception. If you just want to avoid the caller from receiving an object as a result of the constructor call, you could make your constructor throw an exception. If you want them just to receive a null reference, you can't do that in a constructor.

However, you could have a static method instead, which then conditionally calls new or returns null:

public class A
{
    public static A createIfNonNegative(int i)
    {
        return i < 0 ? null : new A();
    }
}
like image 118
Jon Skeet Avatar answered Sep 29 '22 08:09

Jon Skeet