Andrew Coates Andrew Coates - 6 months ago 8
Java Question

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?

Answer

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(typeOfCar == "small"){
    this.capacity = 45;
    this.currentFuel = 45;
}
else {
    this.capacity = 65;
    this.currentFuel = 65;
}
Comments