简体   繁体   中英

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

Probably a basic question. I'm getting an error telling me a blank final field for 'capacity' may not be initialized. Here's my code:

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;
    }
}
}

A car that is small only has a capacity of 45L whereas a large has a capacity of 65L. It only makes sense that the field is final because the capacity isn't going to change. Anyone know how I can make this work?

if you are sure that there will be only 2 typeOfCar (small and large), change the else if condition to else. Clean solution would be to create an Enum for typeOfCar, which can be either SMALL OR LARGE, so the client for Car class cannot send anything else.

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

您应该为轿厢既不大也不小的情况下的容量指定值。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM