Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to stop an object from being created during construction?

Tags:

java

oop

For example if an error occurs inside the constructor (e.g. the parameters pass in were invalid) and I wanted to stop an object being created would it be possible to return null rather than a reference to a new object. (I know the term return is technically correct in this case but you know what I mean).Basically, is it possible to cancel object creation?

Please guide me to get out of this issue...

like image 973
Saravanan Avatar asked Sep 14 '11 04:09

Saravanan


3 Answers

Yes, you can throw an exception, which will terminate object creation. You cannot return null or any other value from a constructor.

like image 65
BeeOnRope Avatar answered Nov 19 '22 07:11

BeeOnRope


If the parameters passed in are invalid, you should throw an IllegalArgumentException with a descriptive message. NullPointerException should be thrown in case of illegal null values.

Here's an example of a BigCar class that requires its engine to be > 4000 CC.

public class BigCar {
    private final Engine engine;

    public BigCar(Engine engine) {
        if (engine == null)
            throw new NullPointerException("Must provide an engine to our car");
        if (engine.getCC() <= 4000)
            throw new IllegalArgumentException(
                    "Engine should be bigger than 4000 CC");
        this.engine = engine;
    }

    public static void main(String... args) {
        // Size of engine is 2000CC
        Engine engine = new Engine(2000);

        BigCar myBigCar = new BigCar(engine); // Exception; Engine should be
                                                // bigger than 4000 CC

    }

}
like image 29
Sahil Muthoo Avatar answered Nov 19 '22 06:11

Sahil Muthoo


Use getters and setters method to set the values for parameters and throw exception if the value is invalid or show a messagebox that object can not be created.

UPDATE

public class A {
private String Name;

public void SetName(String name) {
    if (name.equals(null) || name.equals(""))
        throw new IllegalArgumentException("name can not be null or empty");
}

public A(String name) {
    SetName(name);
}
}

Like this Simon

like image 24
Adnan Bhatti Avatar answered Nov 19 '22 08:11

Adnan Bhatti