I want to extend the Union type in Java generics.

Asked 1 years ago, Updated 1 years ago, 47 views

When specifying the type of Java generic (like the Union type of TypeScript), is it not possible to specify a type such as String or Long type?

Image (?)

class Test <Textends String | extensions Long > {
 ......
}

java java8

2022-09-30 14:58

1 Answers

Because Java cannot be multiple inherited in the first place, a class T cannot extend multiple classes, so even T specified in the generic should follow that principle.

Therefore, in the generics, one extends and one or more implements are combined

class Test<Textends ClassA&InterfaceB&InterfaceC>{
 ......
}

A format like this is possible (Note: Bound Type Parameters: Multiple Bounds), but there is no way to specify multiple classes.


2022-09-30 14:58

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.