samedi 26 novembre 2022

Builder Pattern Null Pointer Exception

I get Null Pointer Exception when running the code below:

public class Engine{

private String name = null;
private Mercedes m = null;

private Engine() {

}

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

public Mercedes getM() {
    return m;
}

public void setM(Mercedes m) {
    this.m = m;
}

public static EngineBuilder builder() {
    return new EngineBuilder();
}

public static class EngineBuilder {
    private Engine e = null;

    public EngineBuilder builder() {
        e = new Engine();
        return this;
    }

    public Engine build() {
        return this.e;
    }

    public EngineBuilder setName(String name) {
        this.e.setName(name);
        return this;
    }

    public EngineBuilder setM(Mercedes m) {
        this.e.setM(m);
        return this;
    }

}
public static void main(String[] args) {
    EngineBuilder builder = Engine.builder();
    builder.setName("test");
            
    Engine e = builder.build();

}

} }

I expected the Builder pattern would work, but I got "Exception in thread "main" java.lang.NullPointerException: Cannot invoke "Engine.setName(String)" because "this.e" is null"

Aucun commentaire:

Enregistrer un commentaire