Is there a way in Java to declare an enumeration whose values can be used together? For example:
enum FileAccess { Read, Write, ReadWrite }
Is it possible to define ReadWrite as Read | Write
(or anything that would yield the same result)?
An enum type is a special data type that enables for a variable to be a set of predefined constants. The variable must be equal to one of the values that have been predefined for it. Common examples include compass directions (values of NORTH, SOUTH, EAST, and WEST) and the days of the week.
Yes, Enum implements an interface in Java, it can be useful when we need to implement some business logic that is tightly coupled with a discriminatory property of a given object or class. An Enum is a special datatype which is added in Java 1.5 version.
Enum, it can not extend any other class or enum and also any class can not extend enum. So it's clear that enum can not extend or can not be extended. But when there is a need to achieve multiple inheritance enum can implement any interface and in java, it is possible that an enum can implement an interface.
No, we cannot extend an enum in Java. Java enums can extend java. lang. Enum class implicitly, so enum types cannot extend another class.
You use EnumSet:
EnumSet<FileAccess> readWrite = EnumSet.of(FileAccess.Read, FileAccess.Write);
This is actually somewhat more elegant than the C#/.NET way, IMO - aside from anything else, you can easily distinguish between a set and a single value.
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