Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can Java Enumerations be merged (like Bitwise in C#)?

Tags:

java

enums

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)?

like image 518
Hosam Aly Avatar asked Jan 02 '09 13:01

Hosam Aly


People also ask

What is the point of enums in Java?

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.

Can we implement enum in Java?

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.

Can enum extend interface?

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.

Can a class extend enum in Java?

No, we cannot extend an enum in Java. Java enums can extend java. lang. Enum class implicitly, so enum types cannot extend another class.


1 Answers

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.

like image 120
Jon Skeet Avatar answered Oct 26 '22 02:10

Jon Skeet