开发者

Difference of Enum between java and C++?

开发者 https://www.devze.com 2022-12-16 11:33 出处:网络
I am learning Enums in java I like to know what are the major differences of Enum in 开发者_高级运维java and C++.

I am learning Enums in java I like to know what are the major differences of Enum in 开发者_高级运维java and C++. Thanks


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.


Enums in C/C++ are plain Integers.

Enums in Java are objects - they can have methods (with different behavior from one enum instance to the other). Moreoever, the enum class supplies methods which allows iteration over all enum instances and lookup of an enum instance.

C++:

typedef enum { Red, Yellow, Green } Colors;

void canCrossIntersection(Colors c) {
   return c == Green;
}

Java:

public enum Colors {
  RED(false),
  Yellow(false),
  Green(true) 
  ;

  Color(boolean b) { this.b = b; }
  private boolean b;

  public boolean canCrossIntersection() { return b; }
}


In Java you can even emulated extensible enums by letting them implement the same interface and then add all of their values to some sort of collection by calling their values() method.


For a semi-answer... C++0x Strongly Typed Enums bring many of the benefits of Java Enums to C++: strong typing, scope and so forth. If your compiler supports C++0x Strongly Typed Enums, you should consider using them.

Reference: http://www2.research.att.com/~bs/C++0xFAQ.html#enum


A great feature of Java Enums which lacks in C++ is the name() method. This way you can get the Enum value name (as written in the enum definition) without any extra line of code in definition. For example:

enum Type {T1, T2, T3}
Type t = Type.T1;   
System.out.println(t.name()); // prints T1
0

精彩评论

暂无评论...
验证码 换一张
取 消