I'm trying to set values to enum in my java application....but I can't do that.
Am I doing it wrong???
public enum RPCPacketDataType {
PT_UNKNOWN(2),
PT_JSON(4),
PT_BINARY(5)
};
It's giving me this error : The constructor RPCPacket.RPCPacketDataType(int) is undefined.
You cannot create an object of an enum explicitly so, you need to add a parameterized constructor to initialize the value(s). The initialization should be done only once. Therefore, the constructor must be declared private or default. To returns the values of the constants using an instance method(getter).
Overview. The Java enum type provides a language-supported way to create and use constant values. By defining a finite set of values, the enum is more type safe than constant literal variables like String or int.
Like Java Classes, Enums can contain Constructors, Member Variables, Methods and also implement Interfaces. However, the only difference is that Enum constants are public, static, and final. Besides, you can instantiate it using the 'new' keyword or extend any other class explicitly.
public enum RPCPacketDataType
{
PT_UNKNOWN(2),
PT_JSON(4),
PT_BINARY(5);
RPCPacketDataType (int i)
{
this.type = i;
}
private int type;
public int getNumericType()
{
return type;
}
}
You can also define methods on your enum as you would in a "normal" class.
System.out.println(RPCPacketDataType.PT_JSON.getNumericType() // => 4
You should create a Contructor which accepts an int
parameter. Also add an int
field which will hold the passed value.
public enum RPCPacketDataType {
PT_UNKNOWN(2),
PT_JSON(4),
PT_BINARY(5);
private int mValue;
RPCPacketDataType(int value) {
mValue = 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