2

I'm trying to define some properties for objects in a game, so I use interfaces to specify them.

I've created a Interactable interface, but then I want to create a Eatable interface, which obviously implements Interactable because the interaction is to eat, but I can't do that because I can't implement a method in an interface.

Is there a workaround?

public interface Interactable {
    void interact();
}

public interface Eatable implements Interactable {
    public void eat();
    public void interact() {
        // Obviously, this doesn't work
        eat();
    }
}
Musa
  • 96,336
  • 17
  • 118
  • 137
Hennio
  • 433
  • 2
  • 18
  • Interfaces can't implement methods - as of Java 7, at least; Java 8 will likely introduce [Default Methods](http://cr.openjdk.java.net/~briangoetz/lambda/lambda-state-4.html) for interfaces. You may want to rethink your design - is inheritance the most appropriate way to add these behaviours to your objects? – McDowell Dec 31 '12 at 15:19

2 Answers2

1

Firstly, Interfaces can only extend another interfaces, make Eatable abstract class and make implement Interactable .

public abstract class Eatable implements Interactable {
    public void eat();
    public void interact() {
        eat();
    }
}
Dave Newton
  • 158,873
  • 26
  • 254
  • 302
PermGenError
  • 45,977
  • 8
  • 87
  • 106
  • The same as the other answer: Thank you for the fast answer! The problem is that I would like to maintain Eatable as an interface, because I would like Apple to implement it, not to extend from it(due to java's multi-implementation: eatable, moveable etc.) – Hennio Dec 10 '12 at 00:57
1

Iterfaces can "extend" other interfaces.

In this case, though, I'd make an Abstract Base Class "Food" or something that implements Interactable, and whose interact() method calls an abstract eat() method.

Travis Addair
  • 427
  • 4
  • 11
  • Thank you for the fast answer! The problem is that I would like to maintain Eatable as an interface, because I would like Apple to implement it, not to extend from it(due to java's multi-implementation: eatable, moveable etc.) – Hennio Dec 10 '12 at 00:56
  • I don't think you'd want Apple to implement all those things directly. In most cases, you'd be better off having a parent (again, Food or whatever) that implements Edible, Movable, etc. It sounds like you're looking for a multiple inheritance solution, but in most cases there's a better -- if less obvious -- single inheritance solution to be found. – Travis Addair Dec 10 '12 at 06:43