I want to create a Potion class with different effects, and my initial approach was to use a switch statement in the constructor to determine the potion's properties. However, this doesn't work because the Potion class inherits from a parent class, Item, which requires values like name and description. Since I need to call super in the constructor to pass these values, I'm struggling to find a way to implement the effect logic properly.
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?
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 JEP-513 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");
}
... which is a bit tidier than simply inserting the switch where pe is.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With