Question

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.

Was it helpful?

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.

OTHER TIPS

By doing

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

You are creating a bounded generic type, T which should have its super class of type Figure

As explained in this thread, there is no difference between definig a generic type which extends an interface or a class.

What compiler makes sure is that, when you create Board, T will be supplied with any concrete class that either extends Figure or implements Figure

Actully you didn't extend the interface. You just create a generic class with the type Cross. The definition of your class merely specifies that the the parameterized type must be derived from Figure, i.e implementing Figure or a derivative from it.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top