Java 如何初始化嵌套在if语句中的最终字段?
可能是个基本问题。我收到一个错误,告诉我“容量”的空白最终字段可能未初始化。这是我的密码:Java 如何初始化嵌套在if语句中的最终字段?,java,constructor,final,Java,Constructor,Final,可能是个基本问题。我收到一个错误,告诉我“容量”的空白最终字段可能未初始化。这是我的密码: 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 C
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;
}
}
}
小型汽车的容量仅为45升,而大型汽车的容量为65升。因为容量不会改变,所以字段是最终字段才有意义。有人知道我是如何做到这一点的吗?如果您确定只有两种类型的汽车(小型和大型),请将else if条件更改为else。干净的解决方案是为typeOfCar创建一个枚举,它可以是小的也可以是大的,这样Car类的客户机就不能发送任何其他内容
if("small".equals(typeOfCar)){
this.capacity = 45;
this.currentFuel = 45;
}
else {
this.capacity = 65;
this.currentFuel = 65;
}
当汽车既不大也不小时,您应该指定容量值。如果typeOfCar是
abc
,将设置为什么容量?此外,糟糕的是,完全忘记了字符串比较。我的错。哦,我现在明白了。因为我要验证输入,所以只需要“else”部分。始终使用String.equals()。“String”==“String”比较引用,而不是字符串的值。