Search code examples
javagenericsinheritanceinterfacemultiple-inheritance

Java implement class in interface


Say I have the following classes:

public abstract class Crop {
}

public abstract class Fruit extends Crop {
}

public interface Edible /* ALWAYS IMPLEMENTED BY A CROP */ {
}

public class Apple extends Fruit implements Edible /* BOTH A CROP AND EDIBLE */ {
}

public class Holly extends Fruit /* NOT EDIBLE */ {
}

public class Wheat extends Crop implements Edible {
}

Now, I want to make sure that every Edible (interface) is a Crop (class).

Why can I not say:

public interface Edible implements Crop {
}

So that Edible itself can only be implemented by classes that extend Crop?

Is there a workaround for this, especially when passing Edible as a generic parameter that requires a Crop?


Solution

  • You cannot implement a Java Class on an Interface. Interfaces can only extend other interfaces. So, in that way, you can declare another interface (and implement it on Crop). Then, you can extend this new interface on Editable.

    This can be something like:

    public abstract class Crop implements NewInterface{
    }
    
    public interface Edible extends NewInterface {
    }