I have these classes.
class RedSocket {} class GreenSocket {} class RedWire {} class GreenWire {}
I have a class that uses 2 generic types
public class Connection<W, S> {}
where W is the type of wire and S is the type of Socket.
I am trying to provide a compile time check to make sure that the socket and wire are the same color.
I tried to do this:
public class Connection<W extends Wire & Color, S extends Socket & Color> {} interface Color {} interface Red extends Color {} interface Green extends Color {} interface Socket {} interface Wire {} class RedSocket implements Socket, Red {} class GreenSocket implements Socket, Green {} class RedWire implements Wire, Red {} class GreenWire implements Wire, Green {}
But this does not really guarantee that the Color used is the same for both types, but still allows me to do this:
public class Connection<W extends Wire & Color, S extends Socket & Color> { public static void main(String[] args) { new Connection<RedWire, GreenSocket>(); new Connection<GreenWire, RedSocket>(); } }
(Why this happens was brilliantly explained by Radiodef here )
How can I provide compile time checking to make sure the socket and wire are the same color?
java generics
mindreader Aug 27 '15 at 8:08 2015-08-27 08:08
source share