Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference of Enum between java and C++?

Tags:

java

c++

I am learning Enums in java I like to know what are the major differences of Enum in java and C++. Thanks

like image 774
giri Avatar asked Jan 17 '10 10:01

giri


People also ask

Is enum used in C?

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.

What is enum for 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.

Does C have enum class?

Enum ClassC++11 has introduced enum classes (also called scoped enumerations), that makes enumerations both strongly typed and strongly scoped.

Is enum in C int?

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.


2 Answers

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();
}
like image 54
josefx Avatar answered Sep 21 '22 07:09

josefx


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.

like image 36
Kent Boogaart Avatar answered Sep 19 '22 07:09

Kent Boogaart