Skip to main content
1 of 2
Caleth
  • 12.4k
  • 2
  • 29
  • 45

You figured out that you can hold onto multiple references, of different parts of a type hierachy, but then kept thinking you had to deal will all the tools in one go.

Rather than figure out a way to identify if a particular tool is a Sword, you can instead loop over tools to do Tool-specific code in a tool loop, Sword-specific code in a sword loop, etc.

This does mean that you are doing some of the calculations in a different order, which is fine for addition, but makes a difference for e.g. text output.

public void printToolsAndTotalStats(){ int totalAtk=0; int totalDef=0; int totalSpeed=0; for(Tool tool : tools){ tool.printInfo(); } for(Sword sword : swords){ totalAtk+=sword.atk; } for(Shield shield : shields){ totalDef+=shield.def; } for(MagicCloth magicCloth : magicCloths){ totalAtk+=magicCloth.atk; totalDef+=magicCloth.def; totalSpeed+=magicCloth.speed; } System.out.println("total atk:"+totalAtk+" , total def:"+totalDef+" , totalSpeed:"+totalSpeed); } 

The other thing that you could do, is lift the stats into Tool, making sure there was an appropriate "empty" representation. In your case they could remain int, defaulting to 0, but if they become more detailed then they would need their own type.

interface Tool { default Optional<Attack> getAttack() { return Optional<Attack>.empty(); } default Optional<Defence> getDefence() { return Optional<Defence>.empty(); } default Optional<Speed> getSpeed() { return Optional<Speed>.empty(); } } class Sword implements Tool { private Attack attack; public Optional<Attack> getAttack() { return Optional<Attack>.of(attack); } } 

etc.

Caleth
  • 12.4k
  • 2
  • 29
  • 45