Switch statement in constructor

I'm new to java and trying to make a console based rpg but I have a problem. I want to make a potion class that can have different effects, so my idea was to use a swtich statement in the constructor but this doesnt work because I have a parent class "Item" that needs values like name or description, so the super function is needed
package Items;
public class Potion extends Item {
private int effect;
private int amount;
public Potion(int effect, int amount) {
switch(effect) {
case 0 -> super("Potion of regeneration", "", "Potion");
case 1 -> super("Potion of attack power", "", "Potion");
}
this.effect = effect;
this.amount = amount;
}
}
In the constructor super isn't a top level statement which it has to be. Is there any way I can work around this?
Answer
In current JDK the call to super must be first line, so you can adjust with these approaches:
public Potion(int effect, int amount) {
super(effect==0 ? "Potion of regeneration": "Potion of attack power", "", "Potion");
this.effect = effect;
this.amount = amount;
}
If your case might be extended, use a helper function:
private static String potion(int effect) {
return switch(effect) {
case 0 -> "Potion of regeneration";
case 1 -> "Potion of attack power";
// Other values here ...
default -> throw new IllegalArgumentException("Unexpected value: "+effect);
};
}
public Potion(int effect, int amount) {
super(potion(effect), "", "Potion");
this.effect = effect;
this.amount = amount;
}
JDK25 should provide flexible constructor bodies as part of Read more which allow inline prologue before super:
public Potion(int effect, int amount) {
String pe = switch(effect) {
case 0 -> "Potion of regeneration";
case 1 -> "Potion of attack power";
// Other values here ...
default -> throw new IllegalArgumentException("Unexpected value: "+effect);
};
super(pe, "", "Potion");
}
Enjoyed this article?
Check out more content on our blog or follow us on social media.
Browse more articles