I've been developing a small text-based RPG game in Java. I've written a story-line and did inventory/armor equipment. I've ran into a problem when it comes to accessing some code though. At the beginning of the game, the user can choose to be an archer/mage/warrior (i'll refer to these as "Jobs" not "class"). Each of these have their own class. But when incorporating them into the game, I find that i'm doing a lot of if-statements to always check if the user is a archer/mage/warrior. How would I better integrate this without using if-statements everywhere? I'm a beginner/intermediate level and doing Objects for about a month now.
-
3Polymorphism, perhaps?Joe C– Joe C2017-08-05 18:24:41 +00:00Commented Aug 5, 2017 at 18:24
-
Read up on subclasses and implementations. The idea is you have a skeleton and provide job-specific code in commonly named methods.Thorbjørn Ravn Andersen– Thorbjørn Ravn Andersen2017-08-05 19:34:28 +00:00Commented Aug 5, 2017 at 19:34
1 Answer
It would be easiest to use polymorphism for this, but this isn't possible if the methods have different names...
If you wanted to do this polymorphically:
First off, read up on polymorphism. Here's a good website to do that.
To start off, have all of your classes extend a superclass, say Player (you will have to write the Player class before you can extend it). To extend the Player class, you can write something like this in the header of your "job" classes:
public class Mage extends Player {
Of course, you substitute Mage for the different classes depending on what "job" you're defining.
Inside the Player class, which you will have to write, you should define all of the methods you want your subclasses to be able to execute. You should make these methods abstract, but keep in mind, if you have an abstract method, you will have to define it in ALL of your subclasses. So, if you had a abstract method called "Cast" you would need to define this in EVERY "job" class.
But once you have created a superclass, with methods, (I suggest having general abstract methods such as Attack or Defend), just define these methods in the subclasses, and you're good to go.
If you want to do this non-polymorphically:
An if-statement, while not necessarily pleasant, appears to be the most effective way to do this, if you don't want to try to make the behaviors polymorphic.
Could you say what the structure of your if-statement is? There might be an easier way to write it, and cut down on the amount of code (to make it more legible).
For example, if you are saying:
if (a.getClass() == X.class)
You could consider using instanceOf instead:
if (a instanceof X)
Besides this, I don't have any better ideas on how to do this.