Java 1.5 Tiger A Developers Notebook [Electronic resources]

David Flanagan, Brett McLaughlin

نسخه متنی -صفحه : 131/ 46
نمايش فراداده

3.10 Manually Defining an Enum

You'll recall from theCreating an Enum, that all enums implicitly extend the new java.lang.Enum class. This class looks a bit like Example 3-10; I've trimmed the method implementations and just left the declarations in for clarity.

Example 3-10. The java.lang.Enum class
package java.lang;
public class Enum<E extends Enum<E>> implements Comparable<E>, Serializable {
protected Enum(String name, int ordinal);
protected Object clone( );
public int compareTo(E o);
public boolean equals(Object other);
public Class<E> getDeclaringClass( );
public int hashCode( );
public String name( );
public int ordinal( );
public String toString( );
public static <T extends Enum<T>> T valueOf(Class<T> enumType, String name);
}

NOTE

This code listing is extracted from the Java 1.5 JavaDoc. Source code isn't available as of the time of this writing.

If you're a bit of a hack, that may get your mind wandering...couldn't I just manually define my own enum, then? Good question.

3.10.1 How do I do that?

You don'tat least, not in Tiger. While this is very much an accessible class, and is indeed the base class of all enumerated types in Tiger, the compiler won't let you extend it, as Example 3-11 tries to do.

Example 3-11. Attempting to extend java.lang.Enum
package com.oreilly.tiger.ch03;
public class ExtendedEnum extends Enum {
}

Attempting to compile this class give you the following error:

[javac] src\ch03\ExtendedEnum.java:3:
classes cannot directly extend java.lang.Enum
[javac] public class ExtendedEnum extends Enum {
[javac]        ^