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...
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.
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
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