public enum Fruit{
APPLE(1),ORANGE(2),BANANA(3);
int code;
Fruit(int code){
this.code=code;
}
}
public final class Fruit extends Enum
{
public static Fruit[] values()
{
return (Fruit[])$VALUES.clone();
}
public static Fruit valueOf(String s)
{
return (Fruit)Enum.valueOf(Fruit, s);
}
private Fruit(String s, int i, int j)
{
super(s, i);
code = j;
}
public static final Fruit APPLE;
public static final Fruit ORANGE;
public static final Fruit BANANA;
int code;
private static final Fruit $VALUES[];
static
{
APPLE = new Fruit("APPLE", 0, 1);
ORANGE = new Fruit("ORANGE", 1, 2);
BANANA = new Fruit("BANANA", 2, 3);
$VALUES = (new Fruit[] {
APPLE, ORANGE, BANANA
});}
}
public abstract class Enum<E extends java.lang.Enum<E>>
implements Comparable<E>, Serializable {
private final String name;
private final int ordinal;
public final String name() {
return name;
}
public final int ordinal() {
return ordinal;
}
protected Enum(String name, int ordinal) {
this.name = name;
this.ordinal = ordinal;
}
public String toString() {
return name;
}
public final boolean equals(Object other) {
return this == other;
}
public final int hashCode() {
return super.hashCode();
}
protected final Object clone() throws CloneNotSupportedException {
throw new CloneNotSupportedException();
}
public final int compareTo(E o) {
java.lang.Enum other = (java.lang.Enum) o;
java.lang.Enum self = this;
if (self.getClass() != other.getClass() && // optimization
self.getDeclaringClass() != other.getDeclaringClass())
throw new ClassCastException();
return self.ordinal - other.ordinal;
}
public final Class<E> getDeclaringClass() {
Class clazz = getClass();
Class zuper = clazz.getSuperclass();
return (zuper == java.lang.Enum.class) ? clazz : zuper;
}
public static <T extends java.lang.Enum<T>> T valueOf(Class<T> enumType,
String name) {
T result = enumType.enumConstantDirectory().get(name);
if (result != null)
return result;
if (name == null)
throw new NullPointerException("Name is null");
throw new IllegalArgumentException(
"No enum constant " + enumType.getCanonicalName() + "." + name);
}
protected final void finalize() {
}
private void readObject(ObjectInputStream in) throws IOException,
ClassNotFoundException {
throw new InvalidObjectException("can't deserialize enum");
}
private void readObjectNoData() throws ObjectStreamException {
throw new InvalidObjectException("can't deserialize enum");
}
}
1. 枚举不允许继承类。Jvm在生成枚举时已经继承了Enum类,由于Java语言是单继承,不支持再继承额外的类(唯一的继承名额被Jvm用了)。
2. 枚举允许实现接口。因为枚举本身就是一个类,类是可以实现多个接口的。
3. 枚举可以用等号比较。Jvm会为每个枚举实例对应生成一个类对象,这个类对象是用public static final修饰的,在static代码块中初始化,是一个单例。
4. 不可以继承枚举。因为Jvm在生成枚举类时,将它声明为final。
5. 枚举本身就是一种对单例设计模式友好的形式,它是实现单例模式的一种很好的方式。
6. 枚举类型的compareTo()方法比较的是枚举类对象的ordinal的值。
7. 枚举类型的equals()方法比较的是枚举类对象的内存地址,作用与等号等价。
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) | 黑马程序员IT技术论坛 X3.2 |