For the enum defined as below
public enum Cars {
SWIFT("Maruti"),
DZIRE("Maruti"),
CIAZ("Maruti"),
I10("Hyundai"),
CRETA("Hyundai");
String company;
Cars(String company){
this.company = company;
}
}
There is Sonar error
Define a constant instead of duplicating this literal "Maruti" 3 times.
If we define static string, it fails to compile
Cannot reference a field before it is defined
Solution 1:
public enum Cars {
SWIFT(CarsString.MARUTI.companyName),DZIRE("Maruti"), I10("Hyundai"), CRETA("Hyundai");
static String MARUTI = "Maruti";
String company;
Cars(String company){
this.company = company;
}
enum CarsString {
MARUTI("maruti"),
HYUNDAI("Hyundai");
String companyName;
CarsString(String companyName){
this.companyName = companyName;
}
}
}
Solution 2:
Not sure if this is the way we do it. When it is not referenced by Cars.MARUTI, it errors out Cannot reference a field before it is defined
.
public enum Cars {
SWIFT(Cars.MARUTI),DZIRE(Cars.MARUTI), I10("Hyundai"), CRETA("Hyundai");
public static final String MARUTI = "Maruti";
String company;
Cars(String company){
this.company = company;
}
}
I have 10 enums in similar state and the above solution 1 didn't much encourage me. Solution 2 solves the purpose,
but why should we refer by
Cars.MARUTI
and notMARUTI
directly? is that a limitation ?
How could we refer a constant value in enum ?