开发者

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

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 i开发者_StackOverflowssue...


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


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

    }

}


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜