Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Validate parameter of constructor before calling superclass constructor

Tags:

For example, constructor like this :

public class Car extends Vehicle {
     public Car(Car a){
         super(a.getName()); //what if 'a' is null 
     }
}

I cannot check condition of parameter before calling super().

like image 956
ldn Avatar asked Nov 30 '18 21:11

ldn


1 Answers

I would recommend to use a factory method in this case:

public class Car extends Vehicle {
    private Car(String name){
        super(name);
    }

    public static Car of(Car a) {
        Objects.requireNonNull(a, "a is required");
        return new Car(a.getName());
    }
}
like image 157
Illya Kysil Avatar answered Nov 29 '22 13:11

Illya Kysil