I have an enum
public enum Days {
SUNDAY, MONDAY, TUESDAY, WEDNESDAY,
THURSDAY, FRIDAY, SATURDAY
}
I want to make a class which can take values of type Days. So I used Java Generics
public class State<T extend Days>
But there is an error
The type parameter T should not be bounded by the final type Days.
Final types cannot be further extended
How can I resolve this?
Java enums will be enhanced with generics support and with the ability to add methods to individual items, a new JEP shows. Since both features can be delivered with the same code change, they are bundled together in the same JEP. The change only affects the Java compiler, and therefore no runtime changes are needed.
We can use also use Enum keyword with Switch statement. We can use Enum in Switch case statement in Java like int primitive.
Generics means parameterized types. The idea is to allow type (Integer, String, … etc., and user-defined types) to be a parameter to methods, classes, and interfaces. Using Generics, it is possible to create classes that work with different data types.
Java allows us to use enum in switch statement. Java enum is a class that represent the group of constants.
enums are final types, which means, you can not extend from them
a generic like wants a Class as Parameter which is Days or an extended class, but the extended class is not possible
so the only parameter possible is Days and you don't need a generic, if only one value is possible
Don't use a generics bound. There's no need. Just use an unbounded type, like this:
public class State<T> {
public State(T startState) {
// whatever
}
}
And to use it:
State<Days> dayState = new State<Days>(Days.SUNDAY);
This is a straightforward typed class that doesn't need a bound.
The only bound that might make sense is a bound to an enum
:
public class State<T extends Enum<T>> {
public State(T startState) {
// whatever
}
}
This version requires that the generic parameter be an enum
. With this version the above usage example would still compile, but this would not compile (for example):
State<String> dayState = new State<String>("hello");
because String
is not an enum
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With