Objective
The union type and intersection type are all equivalent "types"that combine multiple types, and they are not actual types.
Union Type
The union type is constructed using a bit or operator |
:
A | B | C
Note: the use |
of symbols to construct the union type type is only a Java language stipulation, which |
does not represent the meaning of bits or.
In the example above, A | B | C
it is a union type, and the meaning ofunion type is "or", as long as one is satisfied.
Instance: Capturing one of several exceptions
try { // ...} catch (ExceptionA | ExceptionB e) {
is equivalent to:
try { // ...} catch (ExceptionA e) { } catch (ExceptionB e) { }
Intersection Type
The intersection type (intersection type) is performed using bits and operators &
:
A & B & C
intersection type (intersection type), although the name translates to "intersection", the intersection type is not a mathematical intersection meaning. A & B & C
means that the intersection type has A、B、C
characteristics that are equivalent to inheriting the A、B、C
relevant members of each of the two .
Note: in Type1 & Type2 & Type3 & ... & Type n
, you must satisfy: there is at least n-1
one interface, if there are 1 classes that must be placed at the beginning.
Example 1: Generic class
class MyA {}interface MyB {}class Combination extends MyA implements MyB {}class MyC<T extends MyA & MyB> {}public class Test { public static void main(String[] args) { // new MyC<MyA & MyB>(); 报错, <>内不能用Intersection Type new MyC<Combination>(); // OK }}
How to understand <T extends MyA & MyB>
it? Can be MyA & MyB
equivalent to a type U
, which combines MyA
MyB
the characteristics of and, so you can use Combanation
the class as a MyC
type parameter.
Example 2: Forcing type conversions on a lambda expression
public class Test { public static void main(String[] args) { Runnable job =(Runnable & Serializable) () ->System.out.println("Hello"); Class[] interfaces = job.getClass().getInterfaces(); for (Class i : interfaces) { System.out.println(i.getSimpleName()); } }}/*RunnableSerializable
Union Types and intersection Types in Java