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
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();
    }
}
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With