Code Corner: Multiple interface inheritance

multiple inheritance of interface

multiple inheritance of interfaceCan you inherit from an interface twice? This would be pointless unless you throw in generics.  Imagine for example that I have an interface, Basket, which contains a type of fruit (T extends Fruit).  The interface has one method, select(T fruit), so I can take a type of Fruit from the basket. I want to have an implementation of Basket where I implement a Basket of Oranges and a Basket of Apples, from which I could take two types of fruit.

Does this compile?

public interface Fruit {
public class Apple implements Fruit{
public class Orange implements Fruit{
public interface Basket<T> {
    void select(T myFruit);
public class BasketOfApplesAndOrange implements Basket<Apple>, Basket<Orange> {
    public void select(Apple thingToJuggle) {
        System.out.println("Tasty Apple!");
    public void select(Orange thingToJuggle) {
        System.out.println("Tasty Orange!");

And the verdict is….

No! There’s not a chance this will compile. Ten points to you if you got the correct answer. To inherit from an interface twice is illegal in Java. It’s tempting to think that Generics will allow you to get away with it (and I confess I fell for this myself years ago when I was asked it in an interview). But generics are implemented terribly in Java, and one of the consequences is that they are erased away before runtime- better known as type erasure. So at compile time it may be implementing Basket<Orange>, Basket<Apple>, but at runtime this just becomes implements Basket, Basket, which is illegal syntax.

How did you do?  Do you think your colleagues would’ve got the right answer? Challenge them now by sending them this post via Tweet or Facebook.


Photo credit Marcus Spiske


Be the first to leave a comment. Don’t be shy.

Join the Discussion

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>