Skip to main content


Showing posts from February, 2017

Subtyping in Java Generics

Consider the following block of Java code, which we all know as valid - We can do this because Long is a subtype of Number . However, the following will fail to compile - Allowing such assignments would have easily let programmers break the type safety guarantee provided by the Generics . One would then be able to do - From the above example, it is clear that Subtyping in Java Generics works differently than the usual class based Subtyping. A list of numbers cannot point directly to a list of longs even though Long is a subtype of Number . In order to get around this restriction, we will have to use an upper bounded wildcard - which will also allow us to refer to a list of floats as well. A List<? extends Number>   is then treated as something like a super type of both List<Long>  and List<Number> . In fact, as long as a type X  is a subtype of Number , List<? extends Number>  will be able to refer to List<X>  without any compilation errors