Multiple Constrained Type Parameter

This code compiles:

import java.io.Serializable; import java.util.Arrays; class Test<T extends Arrays & Serializable> { } 

but if I replace the last line with

 class Test<T extends Serializable & Arrays> { } 

I get the "interface here". Why?

+8
java generics
source share
2 answers

From JLS Section 4.4 :

Each type variable declared as a type parameter has a binding. If no boundary is declared for the type variable, it is assumed that Object. If a border is declared, it consists of:

  • a variable of the same type T or

  • the class or type of interface T, possibly followed by the interface types I1 and ... and In.

This is a compile-time error if any of the types I1 ... In is a class variable or a type variable.

So basically, if your constraints include a class, this should be the first assessment.

(Given that Arrays cannot be created, it is unclear why you want to link it, think ... was this just an example?)

+13
source share

If one of the bounds is a class, it must be specified first.

0
source share

All Articles