user492052
user492052

Reputation: 151

Creating null reference

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

Upvotes: 5

Views: 201

Answers (4)

khachik
khachik

Reputation: 28703

There are several approaches:

  1. The logic depending of the value of i encapsulated in the same level. In this case condition checking is needed, even if it returns null:
    A a = createAInstance(i);
    if(a == null) { // do something }
    else { // do something else }
    
    so depending on the algorithm you can check the condition at the level where you use A a:
    if(i >= 0) { A a = new A(i); // do something }
    else { // do something else }
    
  2. The logic is implemented in A only: use Null Object to implement a null stub for A, and the code dealing with A instance shouldn't feel the difference;
  3. the logic is mixed: use Null Object as in 2.

Upvotes: 0

Riduidel
Riduidel

Reputation: 22300

As an alternative to Jon Skeet (obviously) excellent answer, you can also throw an exception from constructor :

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);

This way, the object will be constructed (as constructor, by having been called, ensures object exists), but it will indicate clearly that it is not usable.

Upvotes: 3

s.matushonok
s.matushonok

Reputation: 7585

You can use Null Object pattern. In that case object will be created but with logic null state.

Upvotes: 3

Jon Skeet
Jon Skeet

Reputation: 1502606

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();
    }
}

Upvotes: 9

Related Questions