How is Java Enum different from C ++ and regular regular Enum?

How the enum that we get from java 1.5 is different from C ++ and another ordinary Enum type.

+3
java enums
Feb 15 2018-12-15T00:
source share
2 answers

In java enumerations, complex objects are located, while in C ++, each enumeration object is associated with a single integer value. In java, you can have several attributes associated with a single enumeration value:

enum MyCategory { SPORT("The sport category", "sport.png"), NEWS("the news category", "news.jpg"); private String description; private String iconPath; private MyCategory(String description, String iconPath) { this.description = description; this.iconPath = iconPath; } public String getDescription() { return description; } public String getIconPath() { return iconPath; } } 

In addition, in java you can switch only types of numbers, strings and enumerations. However, I can not generalize the usual enumerations in general ...

EDIT Another thing java enumerations can do is declare an operation using a value (taken from a java tutorial ):

 public enum Operation { PLUS { double eval(double x, double y) { return x + y; } }, MINUS { double eval(double x, double y) { return x - y; } }, TIMES { double eval(double x, double y) { return x * y; } }, DIVIDE { double eval(double x, double y) { return x / y; } }; // Do arithmetic op represented by this constant abstract double eval(double x, double y); } 
+5
Feb 15 '12 at 7:55
source share

The Java enums programming language enums much more efficient than their counterparts in other languages, which are more than glorified integers. The new enum declaration defines a full-fledged class (called an enum type). In addition to solving all problems (not types, no namespace, fragility and printed values ​​are uninformative), which exists with the following int Enum pattern , which was used before java 5.0:

 public static final int SEASON_WINTER = 0; 

it also allows you to add arbitrary methods and fields to an enumeration type, implement arbitrary interfaces and much more. Enum types provide high-quality implementations of all Object methods. They are Comparable and Serializable , and the serial form is designed to withstand arbitrary changes in the type of enumeration.

Read more in the Java Enums article.

+3
Feb 15 '12 at 8:26
source share



All Articles