I am learning Enums in java I like to know what are the major differences of Enum in java and C++. Thanks
Enumeration or Enum in C is a special kind of data type defined by the user. It consists of constant integrals or integers that are given names by a user. The use of enum in C to name the integer values makes the entire program easy to learn, understand, and maintain by the same or even different programmer.
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.
Enum ClassC++11 has introduced enum classes (also called scoped enumerations), that makes enumerations both strongly typed and strongly scoped.
In C enum types are just int s under the covers. Typecast them to whatever you want. enums are not always ints in C. However, it is reasonable to assume they are built on integral types.
In c++ an enum is just a list of integer values. In java an enum is a class which extends Enum and is more a nice way to write:
class MyEnum extends Enum<MyEnum>
{
public final static MyEnum VE01 = new MyEnum();
public final static MyEnum VE02 = new MyEnum();
}
as enum:
enum MyEnum
{
VE01,VE02;
}
For the Methods of enum see this. Since a java enum is an object it supports everything a normal java object does. as giving them values or functions:
enum Binary{
ZERO(0),ONE(1);
Binary(int i)
{
value = i;
}
public final int value;
}
a nice one is anonymous classes:
enum State{
StateA{
public State doSomething()
{
//state code here
return StateB;
}
},
StateB{
public State doSomething()
{
return StateA;
}
};
public abstract State doSomething();
}
In C++, an enumeration is just a set of named, integral constants. In Java, an enumeration is more like a named instance of a class. You have the ability to customize the members available on the enumeration.
Also, C++ will implicitly convert enum values to their integral equivalent, whereas the conversion must be explicit in Java.
More information available on Wikipedia.
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