如何初始化嵌套在 if 语句中的最终字段?

How can I initialize a final field that is nested in an if statement?

可能是一个基本问题。我收到一条错误消息,提示 'capacity' 的空白最终字段可能未初始化。这是我的代码:

public class Car {

private final RegNoInterface regNo;
private final String typeOfCar;
private final int capacity;
private boolean outForRent;
private boolean tankFull;
private int currentFuel;

public Car(RegNoInterface regNo, String typeOfCar){
    //validate inputs
    this.regNo = regNo;
    this.typeOfCar = typeOfCar;

    if(typeOfCar == "small"){
        this.capacity = 45;
        this.currentFuel = 45;
    }
    else if(typeOfCar == "large"){
        this.capacity = 65;
        this.currentFuel = 65;
    }
}
}

小车只有45L,大车有65L。只有字段是最终的才有意义,因为容量不会改变。有谁知道我该怎么做?

如果您确定只有 2 个 typeOfCar(小和大),请将 else if 条件更改为 else。干净的解决方案是为 typeOfCar 创建一个枚举,它可以是小的也可以是大的,因此 Car class 的客户端无法发送任何其他内容。

if("small".equals(typeOfCar)){
    this.capacity = 45;
    this.currentFuel = 45;
}
else {
    this.capacity = 65;
    this.currentFuel = 65;
}

当车子既不大也不小时,您应该指定容量值。