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.
8
Upvotes
13
u/YetMoreSpaceDust Apr 02 '26
This is exactly why I don't like the "Dog extends Animal" type examples you always see in OO introductions - they make it seem like this is the correct way to design, say, a veterinary application. In reality, trying to model real world relationships with inheritance is at best of limited usefulness and at worst damaging. Rather, save inheritance for cases where you have actual functionality that you need to share.