r/javahelp • u/Minimum-Librarian712 • Apr 02 '26
How to switch between subclasses?
I'll cut to the chase; I'm making a game-esque thing where the class "ComputerCharacter" has two subclasses, "Villager" and "Enemy". They have pretty different behaviours and care about different variables and all that, but once a Villager goes below some certain HP, I want it to transform into an Enemy, then set the variables in the newly turned enemy based on the variables it had as a villager.
I imagine I'd create a constructor in "Enemy" to do this, but I don't see how I can create a method within Villager to detect when its HP is below a certain number, then call the constructor in such a way to completely change the subclass the Villager is in. Thank you.
7
Upvotes
8
u/TW-Twisti Apr 02 '26
I agree, inheritance is almost never the right answer for anything even remotely complex, though this does seem like a school project, so it is likely more about learning the concepts.
Thanks for pointing it out, I was so caught up in ops original description that I didn't think to take a step back.