Enum -- just sugar to Class
In Pathashala training, there was one exercise which models Metrics,Units etc.
Enum was Unit, UnitSubtype.
Lesson : Enum is just sugar to class.This means all the functionality which can be provided by Enum can be provided by class. In fact internally enum converted to class.
Exercise :
Prove above statement and change your code to use class instead of Enum.
Solution :
To prove :
Take sample enum say Color. Get class file. In command line, run javap Color.
enum Colors{
RED,GREEN,BLUE;
}
javap Colors
Compiled from "Colors.java"
final class Colors extends java.lang.Enum<Colors> {
public static final Colors RED;
public static final Colors GREEN;
public static final Colors BLUE;
public static Colors[] values();
public static Colors valueOf(java.lang.String);
static {};
}
You can see declarations etc.
This proves that Enum is just sugar to class.
Enum was Unit, UnitSubtype.
Lesson : Enum is just sugar to class.This means all the functionality which can be provided by Enum can be provided by class. In fact internally enum converted to class.
Exercise :
Prove above statement and change your code to use class instead of Enum.
Solution :
To prove :
enum Colors{
RED,GREEN,BLUE;
}
javap Colors
Compiled from "Colors.java"
final class Colors extends java.lang.Enum<Colors> {
public static final Colors RED;
public static final Colors GREEN;
public static final Colors BLUE;
public static Colors[] values();
public static Colors valueOf(java.lang.String);
static {};
}
You can see declarations etc.
This proves that Enum is just sugar to class.
Comments
Post a Comment