Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generic Generics: "Syntax error on token "extends", , expected"

Tags:

java

generics

public interface View{...

public interface Control<V extends View>{...

public class RemoteControl<C extends Control<V extends View>> implements Control<V>{...

gives me a "Syntax error on token "extends", , expected" on "V extends View" for the RemoteControl class.

I guess the following alternative was possible

public class RemoteControl<C extends Control<V>,V extends View> implements Control<V>
{...

Still I wonder if this cannot be done in a more implicit way since the latter would require a redundant declaration of the View. I.e.:

public class TVRemoteControl extends RemoteControl<TVControl,TvView> implements TVControl{...

vs

public class TVRemoteControl extends RemoteControl<TVControl> implements TVControl{...

Maybe I'm just stuck in a box again, but is it possible to get the "generic Generics" in a more elegant way

like image 355
Roland Avatar asked Feb 19 '13 08:02

Roland


1 Answers

You suggest:

I guess the following alternative was possible

public class RemoteControl<C extends Control<V>,V extends View> implements Control<V>{}

This is the correct solution, although I would normally write it as (for readability):

public class RemoteControl<V extends View, C extends Control<V>> implements Control<V>{}

You are typing RemoteControl on a Control object which is also typed on an object that extends View. As such you need to provide the implementation of View that types the Control object that types your RemoteControl object.

I guess you could interpret your question as saying, why do I have to provide V - shouldn't it be implied from the <C extends Control<V>>. To which, the answer is no, you need to provide a type for V to ensure that the right type of Control is provided (i.e. that it extends Control<V>)

If you don't care what type View the Control object is typed on, you don't need to type Control in the RemoteControl:

public class RemoteControl<C extends Control> implements Control{}

However, the fact Control is typed on V extends View and RemoteControl implements Control<V>, rather suggests that you do...

like image 175
amaidment Avatar answered Oct 10 '22 09:10

amaidment