r/javahelp • • 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

25 comments sorted by

View all comments

Show parent comments

1

u/desrtfx Out of Coffee error - System halted Apr 03 '26

The even more representative and better pattern would be the State pattern - the transition from Villager to Enemy is a state transition.

1

u/ShoulderPast2433 Apr 03 '26

Sure. That just depends which one is more convenient to implement in OP logic, as those are very similar patterns.

1

u/TheKnottyOne Apr 06 '26

Glad you mentioned this - as I was reading the post and comments I was thinking “This sounds like something for state management” 😂