Reputation: 151
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
Reputation: 28703
There are several approaches:
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 }
Upvotes: 0
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
Reputation: 7585
You can use Null Object pattern. In that case object will be created but with logic null state.
Upvotes: 3
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