Enum类

目录

jdk1.5以前,需要自定义枚举类

jdk1.5以后使用enum关键字

枚举类默认继承了java.lang.Enum,所以不能再继承其他类,而且该类是一个final类,不能被继承

使用无参构造器创建枚举对象,实参列表和小括号都可以省略

 java.lang.Enum源码

 相同的枚举对象使用==,结果为true

java.lang.Enum方法测试

枚举类可以实现接口


jdk1.5以前,需要自定义枚举类

  • 枚举类对象的属性不应允许被改动, 所以应该使用private final修饰
  • 枚举类的使用private final 修饰的属性应该在构造器中为其赋值
  • 若枚举类显式的定义了带参数的构造器, 则在列出枚举值时也必须对应的传入参数
public class SeasonTest {
	
	
	public static void main(String[] args) {
		
		Season spring=Season.SPRING;
		System.out.println(spring);//season=春天,这是调用的重写的toString
		
	}

}


//jdk1.5之前自定义枚举类
//枚举类的特点,类的对象只有有限个
class Season{
	
	//声明属性,不能被修改的属性值
	
	private final String seasonName;
	private final String seasonDesc;
	
	// 私有化构造器,并给对象属性赋值
	private Season(String seasonName,String seasonDesc) {
		
		this.seasonDesc=seasonDesc;
		this.seasonName=seasonName;	
	}
	
	//提供多个枚举类的对象,要想直接使用类名获取对象,则需要static修饰
	public static final Season SPRING=new Season("春天","万物复苏");
	public static final Season SUMMER=new Season("夏天","热的中暑");
    public static final Season AUTUMN = new Season("秋天","金秋送爽");
	public static final Season WINTER = new Season("冬天","白雪皑皑");
	    
	//其他诉求,获取枚举类的属性
	
	public String getSeasonDesc() {
		return seasonDesc;
	}
	
	public String getSeasonName() {
		return seasonName;
	}
	
	//提供toString
	@Override
	public String toString() {
		// TODO Auto-generated method stub
		return "season="+this.getSeasonName();
	}
	
}

jdk1.5以后使用enum关键字

  • 使用enum定义的枚举类默认继承了java.lang.Enum类,因此不能再继承其他类
  • 枚举类的构造器只能使用private 权限修饰符
  • 枚举类的所有实例必须在枚举类中显式列出(, 分隔; 结尾)。列出的实例系统会自动添加public static final 修饰

/**
 * 使用enum关键字定义枚举类
 * 说明:定义的枚举类默认继承于java.lang.Enum类
 */
public class SeasonTest1 {
	
	public static void main(String[] args) {
		Season1 summer=Season1.SUMMER;
		System.out.println(summer);//SUMMER,调用父类java.lang.Enum.toString()
	}

}

//关键字enum,没有class
enum  Season1{
	
	//1.提供当前枚举类多个对象,逗号分隔,分号结尾
	SPRING("春天","万物复苏"),
	SUMMER("夏天","热的中暑"),
    AUTUMN("秋天","金秋送爽"),
	WINTER("冬天","白雪皑皑");
	
    //2.声明对象属性,使用 private final
	
	private final String seasonName;
	private final String seasonDesc;
	
	//3.私有化构造器,给属性赋值
	
    private Season1(String seasonName,String seasonDesc) {
		
		this.seasonDesc=seasonDesc;
		this.seasonName=seasonName;	
	}
    
    //其他方法等
	
	
	
}

枚举类默认继承了java.lang.Enum,所以不能再继承其他类,而且该类是一个final类,不能被继承

如何证明:使用javap进行反编译

使用无参构造器创建枚举对象,实参列表和小括号都可以省略

public class GenderTest {
	
	public static void main(String[] args) {
		System.out.println(Gender.BOY);//BOY
     
		
	}

}

enum Gender{
	
	/**
	 * 源码分析   java.lang.Enum
	     这个就是常量的名字
	 *   private final String name;
	 *   
	    protected Enum(String name, int ordinal) {
	     
	        this.name = name;
	        this.ordinal = ordinal;
	    }
	    
	    toString
	     public String toString() {
        return name;
    }
    
    
	 */
	//java.lang.Enum
	GIRL,BOY();//使用的是无参构造器,GRIL()}
	
}

 java.lang.Enum源码

相关属性和方法

 

/*
 * Copyright (c) 2003, 2011, Oracle and/or its affiliates. All rights reserved.
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * This code is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License version 2 only, as
 * published by the Free Software Foundation.  Oracle designates this
 * particular file as subject to the "Classpath" exception as provided
 * by Oracle in the LICENSE file that accompanied this code.
 *
 * This code is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 * version 2 for more details (a copy is included in the LICENSE file that
 * accompanied this code).
 *
 * You should have received a copy of the GNU General Public License version
 * 2 along with this work; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 *
 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
 * or visit www.oracle.com if you need additional information or have any
 * questions.
 */

package java.lang;

import java.io.Serializable;
import java.io.IOException;
import java.io.InvalidObjectException;
import java.io.ObjectInputStream;
import java.io.ObjectStreamException;

/**
 * This is the common base class of all Java language enumeration types.
 *
 * More information about enums, including descriptions of the
 * implicitly declared methods synthesized by the compiler, can be
 * found in section 8.9 of
 * <cite>The Java&trade; Language Specification</cite>.
 *
 * <p> Note that when using an enumeration type as the type of a set
 * or as the type of the keys in a map, specialized and efficient
 * {@linkplain java.util.EnumSet set} and {@linkplain
 * java.util.EnumMap map} implementations are available.
 *
 * @param <E> The enum type subclass
 * @author  Josh Bloch
 * @author  Neal Gafter
 * @see     Class#getEnumConstants()
 * @see     java.util.EnumSet
 * @see     java.util.EnumMap
 * @since   1.5
 */
public abstract class Enum<E extends Enum<E>>
        implements Comparable<E>, Serializable {
    /**
     * The name of this enum constant, as declared in the enum declaration.
     * Most programmers should use the {@link #toString} method rather than
     * accessing this field.
     */
    private final String name;

    /**
     * Returns the name of this enum constant, exactly as declared in its
     * enum declaration.
     *
     * <b>Most programmers should use the {@link #toString} method in
     * preference to this one, as the toString method may return
     * a more user-friendly name.</b>  This method is designed primarily for
     * use in specialized situations where correctness depends on getting the
     * exact name, which will not vary from release to release.
     *
     * @return the name of this enum constant
     */
    public final String name() {
        return name;
    }

    /**
     * The ordinal of this enumeration constant (its position
     * in the enum declaration, where the initial constant is assigned
     * an ordinal of zero).
     *
     * Most programmers will have no use for this field.  It is designed
     * for use by sophisticated enum-based data structures, such as
     * {@link java.util.EnumSet} and {@link java.util.EnumMap}.
     */
    private final int ordinal;

    /**
     * Returns the ordinal of this enumeration constant (its position
     * in its enum declaration, where the initial constant is assigned
     * an ordinal of zero).
     *
     * Most programmers will have no use for this method.  It is
     * designed for use by sophisticated enum-based data structures, such
     * as {@link java.util.EnumSet} and {@link java.util.EnumMap}.
     *
     * @return the ordinal of this enumeration constant
     */
    public final int ordinal() {
        return ordinal;
    }

    /**
     * Sole constructor.  Programmers cannot invoke this constructor.
     * It is for use by code emitted by the compiler in response to
     * enum type declarations.
     *
     * @param name - The name of this enum constant, which is the identifier
     *               used to declare it.
     * @param ordinal - The ordinal of this enumeration constant (its position
     *         in the enum declaration, where the initial constant is assigned
     *         an ordinal of zero).
     */
    protected Enum(String name, int ordinal) {
        this.name = name;
        this.ordinal = ordinal;
    }

    /**
     * Returns the name of this enum constant, as contained in the
     * declaration.  This method may be overridden, though it typically
     * isn't necessary or desirable.  An enum type should override this
     * method when a more "programmer-friendly" string form exists.
     *
     * @return the name of this enum constant
     */
    public String toString() {
        return name;
    }

    /**
     * Returns true if the specified object is equal to this
     * enum constant.
     *
     * @param other the object to be compared for equality with this object.
     * @return  true if the specified object is equal to this
     *          enum constant.
     */
    public final boolean equals(Object other) {
        return this==other;
    }

    /**
     * Returns a hash code for this enum constant.
     *
     * @return a hash code for this enum constant.
     */
    public final int hashCode() {
        return super.hashCode();
    }

    /**
     * Throws CloneNotSupportedException.  This guarantees that enums
     * are never cloned, which is necessary to preserve their "singleton"
     * status.
     *
     * @return (never returns)
     */
    protected final Object clone() throws CloneNotSupportedException {
        throw new CloneNotSupportedException();
    }

    /**
     * Compares this enum with the specified object for order.  Returns a
     * negative integer, zero, or a positive integer as this object is less
     * than, equal to, or greater than the specified object.
     *
     * Enum constants are only comparable to other enum constants of the
     * same enum type.  The natural order implemented by this
     * method is the order in which the constants are declared.
     */
    public final int compareTo(E o) {
        Enum<?> other = (Enum<?>)o;
        Enum<E> self = this;
        if (self.getClass() != other.getClass() && // optimization
            self.getDeclaringClass() != other.getDeclaringClass())
            throw new ClassCastException();
        return self.ordinal - other.ordinal;
    }

    /**
     * Returns the Class object corresponding to this enum constant's
     * enum type.  Two enum constants e1 and  e2 are of the
     * same enum type if and only if
     *   e1.getDeclaringClass() == e2.getDeclaringClass().
     * (The value returned by this method may differ from the one returned
     * by the {@link Object#getClass} method for enum constants with
     * constant-specific class bodies.)
     *
     * @return the Class object corresponding to this enum constant's
     *     enum type
     */
    @SuppressWarnings("unchecked")
    public final Class<E> getDeclaringClass() {
        Class<?> clazz = getClass();
        Class<?> zuper = clazz.getSuperclass();
        return (zuper == Enum.class) ? (Class<E>)clazz : (Class<E>)zuper;
    }

    /**
     * Returns the enum constant of the specified enum type with the
     * specified name.  The name must match exactly an identifier used
     * to declare an enum constant in this type.  (Extraneous whitespace
     * characters are not permitted.)
     *
     * <p>Note that for a particular enum type {@code T}, the
     * implicitly declared {@code public static T valueOf(String)}
     * method on that enum may be used instead of this method to map
     * from a name to the corresponding enum constant.  All the
     * constants of an enum type can be obtained by calling the
     * implicit {@code public static T[] values()} method of that
     * type.
     *
     * @param <T> The enum type whose constant is to be returned
     * @param enumType the {@code Class} object of the enum type from which
     *      to return a constant
     * @param name the name of the constant to return
     * @return the enum constant of the specified enum type with the
     *      specified name
     * @throws IllegalArgumentException if the specified enum type has
     *         no constant with the specified name, or the specified
     *         class object does not represent an enum type
     * @throws NullPointerException if {@code enumType} or {@code name}
     *         is null
     * @since 1.5
     */
    public static <T extends 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);
    }

    /**
     * enum classes cannot have finalize methods.
     */
    protected final void finalize() { }

    /**
     * prevent default deserialization
     */
    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");
    }
}

 

 相同的枚举对象使用==,结果为true

对象用的static final修饰,相当于常量

java.lang.Enum方法测试

package enums;



public class SeasonTest1 {
	
	public static void main(String[] args) {
		//方法测试 toString(),返回当前对象名字,若是子类重写了则返回子类写的属性信息
		Season1 winter=Season1.WINTER;
		System.out.println(winter);//WINTER
		
		//name() 返回当前对象名
		System.out.println(winter.name());
        
		//ordinal() 返回当前对象位置号
		System.out.println(winter.ordinal());
		System.out.println("*************");
		//values 返回当前枚举类所有对象
		Season1[] values = winter.values();
		for(Season1 item:values) {
			System.out.println(item);
		}

		//valueOf 将字符串转换为枚举对象,但是这个字符串必须是该枚举类存在的对象,否则抛出异常
		System.out.println("********");
		Season1 spring = winter.valueOf("SPRING");
		System.out.println(spring);
		
		//compareTo 比较两个枚举常量,比较的是位置号
		System.out.println(Season1.SPRING.compareTo(Season1.SUMMER));
	}
	
	/**
	 * 
	输出结果
	WINTER
	3
	*************
	SPRING
	SUMMER
	AUTUMN
	WINTER
	********
	SPRING
	-1

	 * 
	 * 
	 * 
	 */

}

//关键字enum,没有class
enum  Season1{
	
	//1.提供当前枚举类多个对象,逗号分隔,分号结尾
	SPRING("春天","万物复苏"),
	SUMMER("夏天","热的中暑"),
    AUTUMN("秋天","金秋送爽"),
	WINTER("冬天","白雪皑皑");
	
    //2.声明对象属性,使用 private final
	
	private final String seasonName;
	private final String seasonDesc;
	
	//3.私有化构造器,给属性赋值
	
    private Season1(String seasonName,String seasonDesc) {
		
		this.seasonDesc=seasonDesc;
		this.seasonName=seasonName;	
	}
    
    //其他方法等
	
	
	
}

枚举类可以实现接口

 

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Java中,enum是一种特殊的,用于定义一组常量。通过使用enum关键字,我们可以在一个enum中添加多个枚举。 enum是一种高级数据型,它可以包含固定数量的元素,这些元素代表一组相关的常量。每个枚举元素都是enum的一个实例,并且具有唯一的名称。 为了添加枚举,我们可以在enum的声明中使用逗号将枚举元素分隔开来。每个枚举元素就像是一个常量,可以给它们一个名称。下面是一个示例: ``` enum Day { MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY } ``` 在这个例子中,我们创建了一个名为Day的enum,并添加了七个枚举元素,分别代表一周中的每一天。 我们可以通过使用枚举的名称和枚举元素的名称来引用它们。例如,使用Day.MONDAY可以引用MONDAY枚举元素。 通过为每个元素分配不同的值,我们可以在enum中添加更多的信息。例如,我们可以为每个枚举元素指定一个字符串值,以便表示不同的周几。下面是一个带有字符串值的示例: ``` enum Day { MONDAY("星期一"), TUESDAY("星期二"), WEDNESDAY("星期三"), THURSDAY("星期四"), FRIDAY("星期五"), SATURDAY("星期六"), SUNDAY("星期日"); private String chineseName; private Day(String name) { chineseName = name; } public String getChineseName() { return chineseName; } } ``` 在这个示例中,我们通过一个私有的构造函数为每个枚举元素指定了一个中文名称,并提供了一个用于获取中文名称的公共方法getChineseName()。 总结来说,通过在enum的声明中使用逗号分隔的枚举元素,我们可以添加枚举。枚举元素可以通过名称引用,还可以为每个元素添加一些信息。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值