0

I am a Java beginner. My problem is, for example:

  • Fire: DMG +1
  • Stone: DEF +1

By combining to:

  • Fire-stone: fire + stone, and inherit both their properties (DMG 1, DEF 1).

  • Flame: fire + fire, and inherit 2 fire properties (DMG +2).

I've played around with classes and interfaces but doesn't seem to work. It seems to me that Java doesn't support multiple inheritance but multiple interfaces. I wonder how I could code each class/interface for this to work?

public static int DMG, DEF = 0;
public static String DESC = "";

interface fire {
    DMG = 1; }

interface stone {
    DEF = 1; }

class firestone implements fire, stone {
    DESC = "Born in fire and stone";
    //DMG and DEF calculations
}
trotta
  • 1,232
  • 1
  • 16
  • 23
mrchoc0
  • 67
  • 5

1 Answers1

0

You better use composition, here is what you could do:

public class Main {
public static void main(String[] args) {
    Tool firestone = new Tool(new Fire(), new Stone());
}

private static interface Component {
    int getDmg();
    int getDef();
}

private static class Fire implements Component {
    @Override
    public int getDmg() {
        return 1;
    }

    @Override
    public int getDef() {
        return 0;
    }
}

private static class Stone implements Component {
    @Override
    public int getDmg() {
        return 0;
    }

    @Override
    public int getDef() {
        return 1;
    }
}

private static class Tool implements Component {
    List<Component> components;
    int dmg;
    int def;

    public Tool(Component... component) {
        components = new ArrayList<>();
        components.addAll(Arrays.asList(component));
        dmg = 0;
        def = 0;
        for (Component c : components) {
            dmg += c.getDmg();
            def += c.getDef();
        }
    }

    @Override
    public int getDmg() {
        return dmg;
    }

    @Override
    public int getDef() {
        return def;
    }
}}

My implementation may be an overkill :P but it is extendable and you add more components that are more and more complicated.

anthony yaghi
  • 532
  • 2
  • 10
  • Thanks! It works like a charm. Is there anyway to show an item/tool's composition? (e.g. Firestone makes of fire and stone) It would be used to help calculating the materials (Fire, Stone etc.) needed to build an item. – mrchoc0 Jul 05 '19 at 17:53
  • Yes sure, you can iterate over the components in the Tool class and then you have a few options: 1) If by show you mean print the name of the components then you can add a methods to the Component interface, say String getDescription() and then have a different implementation in Fire and Stone. This way you can in the loop call this method on each component and print its name. 2) If you want to tell what each component is programatically then you can use "instanceOf" (google an example), but a better way would be something like a visitor pattern. – anthony yaghi Jul 06 '19 at 05:55