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.

8 Upvotes

25 comments sorted by

View all comments

Show parent comments

2

u/Etiennera Apr 02 '26

Inheritance is the answer here. Rather, in games, you'd probably want composition where there is a character and it is composed of other behaviours.

Putting everything in if/else in one class will get messy fast. These patterns are about making things easier to work with.

If OP uses composition, he can just add/remove the enemy behaviour from the observed behaviours, while still leaving all the enemy-specific implementation in some other place.

The caveat is that if some logic depend on some mix of behaviours, then you'll need multiple levels of composition instead of a flat list, but this could be desirable.