I am following the book and there is an example of enumeration. So I am doing this:
enum Color {
GREEN("GREEN"),
YELLOW("YELLOW"),
RED("RED");
String name;
Color(String name) {
this.name = name;
}
public String getColor() {
return name;
}
}
and then I want to create Objects and return the color through my class like this:
class TrafficLight extends enum<Color> { // I am getting an error:
// Classes cannot directly extend java.lang.Enum
// ...create objects and etc.
}
How can I fix this error? Because this is exactly the same syntax from my book and do not know how to make it correct.
EDIT: my book syntax:
enum Suit {
CLUBS("CLUBS"),
DIAMONDS("DIAMONDS"),
HEARTS("HEARTS"),
SPADES("SPADES");
String name;
Suit(String name) { this.name = name; }
public String toString() { return name; }
}
class Suit extends Enum<Suit> // pseudo-code only
implements Comparable<Suit>, Serializable {
public static final Suit CLUBS = new Suit("CLUBS");
public static final Suit DIAMONDS = new Suit("DIAMONDS");
public static final Suit HEARTS = new Suit("HEARTS");
public static final Suit SPADES = new Suit("SPADES");
String name;
Suit(String name) { this.name = name; }
public String toString() { return name; }
// ... compiler generated methods ...
}
Look carefully.
Compare this:
class TrafficLight extends enum<Color>
with this
class Suit extends Enum<Suit>
Java is case-sensitive. Enum<Color>
and enum<Color>
are very different. (The latter is simply not allowed.)
In your example, you're trying to create one enum type which uses a different enum for the type argument (TrafficLight
and Color
). In the sample code, the enum type uses the same enum type (Suit
) for both the declaration and the type argument.
Did you spot this?
// pseudo-code only
You shouldn't expect pseudo-code to compile.
See more on this question at Stackoverflow