have this enum file containing some information:
public enum Constants {
AGED_BRIE("Aged Brie");
private final String label;
Constants(String label) {
this.label = label;
}
public String getLabel() {
return label;
}
}
this Item class:
public class Item {
public String name;
public Item(String name) {
this.name = name;
}
}
and this factory method:
public class Factory {
public void try(Item item) {
String brie = Constants.AGED_BRIE.getLabel(); // contains "Aged Brie"
switch (item.name) {
case brie -> System.out.println("Hello World"); // Constant expression required
// other cases ...
}
}
}
Unfortunately I get:
Constant expression required
and IntelliJ highlights case label statement.
- What am I missing?
You can't have a method named
try. You need your case(s) to expand to constants. You shouldn't make fields public. But let's start by makingConstantsintoCheese. Like,Now in
Item, instead ofString(s) we want to use theenumtype so you have something to match on in constant expressions later. Not changingConstantswould have made this confusing. Like,Now, we can actually use that for our
case(s). It's aFactory. We canmakethings. Like,