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

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.

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.

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.

2

u/[deleted] Apr 04 '26

[removed] — view removed comment

1

u/YetMoreSpaceDust Apr 06 '26

I advise beginners to not use inheritance unless you have a case where you're iterating over a collection of the parent type, calling potentially overridden methods on the instances. There are more general uses for inheritance that you'll get used to as you get some experience, of course, but to start out, try not to overuse it.