-1

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?

Andrew Coates
  • 119
  • 2
  • 12

2 Answers2

3

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;
}
Vijay
  • 542
  • 4
  • 15
0

You should specify the value of capacity for the case when the car neither large nor small.