'Are there any use cases for using a final class, enum or record type as a type parameter bound?

You can restrict type parameters with a bound in Java. For example:

interface Foo<T extends Bar> {
    // ...
}

You can use many kinds of types for the bound, including interfaces, classes, parameterized types and type parameters. In other words: Bar can be an interface, a class, etc. (it can't be a primitive or an array type).

You can also use final classes, enum and record types as bounds. So the above still works when Bar is a final class, enum or record.

But enum and record types are implicitly final - it's not possible to create a subtype of an enum or record. This implies that when you use an enum or record as a type parameter bound, then the only possibility to fill in the type parameter is with that specific enum or record type itself as the type argument. The same goes for final classes.

It makes no sense to have a Foo<T> if T cannot be anything other than Bar itself; in that case you could just as well leave out the type parameter from Foo entirely and directly use Bar.

Are there cases in which it makes sense that you can use a final class, enum or record type as a type parameter bound?



Solution 1:[1]

Are there cases in which it makes sense that you can use a final class, enum or record type as a type parameter bound?

No.

See Angelika Langer's FAQ for example. There are no useful applications of such bounds.


Why is it allowed then?
Pass!

One potential explanation though: it keeps the language simpler. Additional constraints require additional checking, thus additional implementation cost.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1