Note that there are some explanatory texts on larger screens.

plurals
  1. POInitializing a lot of fields - constructor vs method return values
    text
    copied!<p>I'm currently working on a Java trading card game, similar to the old Pokémon one. What I now want to do is to define all the cards in some way, but because there's a lot of fields that need to be initialized, I'm thinking of alternative ways, because a constructor will be very long and hardly readable for each card. I also have to initialize the attacks which means I have to basically create an anonymous inner class (is the term correct?) every time, like so:</p> <pre><code>/** * Base set Abra 43/102 */ public final class Abra extends Pokemon { public Abra() { super( new ImageIcon("img/scans/base-set/43-abra.jpg"), "Abra", "Base Set Abra", null, Type.PSYCHIC, Type.PSYCHIC, Type.NONE, 30, 0 ); attack1 = new Attack("Psyshock", Type.NORMAL) { /** * 10 damage. Flip a coin. If heads, the Defending Pokémon is now Paralyzed. */ public void doAttack() { damageApplyWeaknessAndResistance(10); if (gui.frames.CoinFlipDialog.showCoinFlipFrame() == CoinFlip.COIN_HEADS) { Game.getOpponentPlayer().getActivePokemon().status = Status.Paralyzed; } } }; attack2 = null; } } </code></pre> <p>So my second option is to make a hierarchy with interfaces and abstract classes, meaning that the values will not be stored in fields, but rather just returned by methods when needed:</p> <pre><code>public interface Card extends Cloneable, MouseListener, MouseMotionListener { public String getFullName(); public ImageIcon getSmallIcon(); public ImageIcon getFullIcon(); } public interface Pokemon extends Card { public String getName(); public int getHPLeft(); public int getMaxHP(); public Type getType(); public Type getWeakness(); public Type getResistance(); public int getRetreatCost(); public Attack getAttack1(); public Attack getAttack2(); } public class Abra extends AbstractPokemon { @Override public Attack getAttack1() { return new Abra.PsyShock(); } @Override public Attack getAttack2() { return null; } @Override public int getMaxHP() { return 30; } @Override public String getName() { return "Base Set Abra"; } //etc... </code></pre> <p>So my question is: Is any of these methods preferred or is there even any better way?</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload