Search code examples
javainterfacepolymorphismextendsparameterized

Why any type can EXTENDS interface?


Today I got lost in Java polymorphism. I have done something that I have thought that is impossible. Namely - I have EXTENDED interface.

I have created empty interface:

public interface Figure {}

Nothing new right now. Then I have created parametrized class Board with paramether that EXTENDS my interface!

public class Board< T extends Figure > { 
    T[][] board;
}

I thought it is not be possible! Nevertheless I was going further with my not understanding.

I have created class implementing Figure interface:

public class Cross implements Figure{}

And to my suprise I was able to do that:

Board b = new Board<Cross>();

Please help me and explain me this strange situation.
I know a little about polymorphism and I understand that Cross is Figure. I am confused howcome any type is able to EXTEND interface, and howcome classes that implements interaface (not extending interface) are correct as paramether which extends interface.

Please help me and explain this polymorphicall mess. Thanks.


Solution

  • When you say public class Board< T extends Figure >, it means that the Board can accept either Figure or sub-interfaces of Figure or any classes which implement these interfaces. So, when you say:

    public class Cross implements Figure{}
    

    and

    Board b = new Board<Cross>();
    

    This means that Cross has implemented Figure, and thus Board can accept Cross, since Cross IS-A Figure

    As far as extending an interface is concerned, only interfaces can extend interfaces. So, the following is legal:

    public interface TwoDimensionalFigure extends Figure{}.
    

    So any class which implements TwoDimensionalFigure can also be accepted by Board.