Reputation: 563
I don't understand this passage in the Java Language Specification :
The values of an intersection type are those objects that are values of all of the types Ti for 1 ≤ i ≤ n.
As far as I know, it is not possible to directly declare that a variable's type is an intersection type.
The place where I have seen the intersection type used is in the declaration of generic classes, but this seems to have nothing to do with the values of the intersection type. So what do the values of the intersection types mentioned here refer to?
Besides, what is meant by "those objects that are values of all of the types Ti"?
Upvotes: 1
Views: 161
Reputation: 36441
As far as I know, it is not possible to directly declare that a variable's type is an intersection type.
Right, you cannot express an intersection type outside generic context. But you can create object whose type conforms to some intersection type:
class K implement Serializable, Cloneable {...}
var k = new K();
Beware that k
type is not intersection type, it is K
.
But it conforms to an intersection type:
class C {
public static <T extends Serializable & Cloneable> void f(T t) {
}
}
C.f(k);
those objects that are values of all of the types
All instances of classes that implements both Serializable
and Cloneable
are values of all the types.
C.f(k)
is correct because type of k
K
conforms to the contract: be both Serializable
and Cloneable
.
class C {
public static <T extends Serializable & Cloneable> void f(T t) {
var a = (Serializable & Cloneable)t;
t = a; // Wrong!
}
}
Local variable a
is of the intersection type.
And the intersection type is different from T
.
Upvotes: 1
Reputation: 1266
Consider the following code:
public class IntersectionDemo {
interface T1 {
}
interface T2 {
}
static <T extends T1 & T2> void foo(T t) {
}
static class V implements T1, T2 {
}
public static void main(String[] args) {
foo(new V());
}
}
Here the variable t
has the intersection type of T1
and T2
and can accept only reference to object that implements both T1
and T2
, for example reference to object of type V
.
Upvotes: 2