Java does not allow multiple fields to occupy the same memory. There is no direct analog of a C union in Java. So you can't:
- Save memory by having multiple fields occupy the same space, when only one is appropriate at any given time.
- Access one stored value in different representations just by accessing another field in the union (as your second union appears to be intended). Even in C++, this is technically undefined behavior, though some compilers support it.
That said, you can translate code that includes a C union to Java code.
Multiple fields, not saved in same memory
One way is to have multiple fields in a class. Memory will be allocated for each field, even though at most one will be used at any one time.
public class BS2Event { ... // Only one of these can be set char[] userID = new char[BS2_USER_ID_SIZE]; int ioDeviceID; ... }
Single field of base class or interface type
Another way is to represent the union with a single Object or interface pointer that references the one current representation. Memory is allocated within the class only for a single reference, but additional memory is required for the referenced object.
public class BS2Event { // Ordinary struct fields ... private IEntityID m_userOrDeviceID; ... }
Now, m_userID can point to either a UserID or a DeviceID.
public interface IEntityID { ... } public class UserID implements IEntityID { private char[] userID = new char[BS2_USER_ID_SIZE]; ... } private class DeviceID implements IEntityID { private int ioDeviceID; ... }
One representation, accessed in multiple ways
If you have one representation that you want to access in multiple ways, you can do that with methods rather than fields.
public class BS2Event { // Ordinary struct fields ... private Code m_code; ... } private class Code { private int code; public int getCode() { return code; } public short getMainCode() { ... } public short getSubCode() { ... } }
uniondoes. You cannot overlay one type like aFooordoubleover the same memory location as another, like aBarorlong. This is too low-level for Java. You can convert representations like with docs.oracle.com/javase/8/docs/api/java/lang/…, but that doesn't overlay memory. What would you use such a feature for anyway?codeormainCode + subCodein the same location - same asc;)