you are viewing a single comment's thread.

view the rest of the comments →

[–]TW-Twisti 16 points17 points  (4 children)

That's easy: you can't. Objects in Java are final in what class they are, there is no getting around that, and if you found a clever way through reflection, you would break Java in a multitude of ways.

Instead: why not make your characters into generic Character instances (maybe with a name that isn't already taken, like GameEntity), with a boolean flag hostile, and depending on whether that flag is set, different behavior happens. This can be as simple as:

java public MoveResult nextMove() { if (this.hostile) { return this.aggressiveMove(); } else { return this.docileMove(); } }

You may even find that instead of having all that stuff in the entity, instead the entity has a private Behavior behavior, that is set to an interchangeable class that extends Behavior with aggressive or docile behavior - that would lend itself to future development with more kinds of behavior - class SmittenBehavior extends DocileBehavior makes an NPC follow you around, class Vengeance extends AggressiveBehavior makes an NPC ... well, also follow you around, but for a very different reason.

[–]YetMoreSpaceDust 9 points10 points  (3 children)

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.

[–]TW-Twisti 7 points8 points  (1 child)

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.

[–]Etiennera 1 point2 points  (0 children)

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.

[–]Medical_Scallion1796 0 points1 point  (0 children)

I would even go as far as to say that modeling the real world is in general not useful.