枚举与注解详解

枚举和注解

枚举类

把对象一个一个列出来的类称为枚举类,枚举对应英文enum,是一组常量的集合,属于一种特殊的类,里面只包含一组有限的特定的对象(可以作为switch返回值)

自定义实现方法及特点:

  • 1、将构造器私有化

  • 2、删去setXxx方法,可以有get方法

  • 3、对枚举对象/属性用final + static 修饰,实现优化(在使用枚举对象的时候不需要加载枚举类)

  • 4、枚举对象根据需要,可以创建多个属性

  • 枚举名一般都大写(final修饰的都大写)

  • 实例:

    public class Enum01 {
        public static void main(String[] args) {
            System.out.println(Season.AUTUMN.getName());
            System.out.println(Season.SPRING.getName());
        }
    }
    
    //演示枚举实现
    class Season{
        private String name;
        private String desc;
        //1、将构造器私有化,防止直接new
        private Season(String name, String desc) {
            this.name = name;
            this.desc = desc;
        }
        //2、去掉setXxx方法,防止属性修改
    
    //
    //    public void setName(String name) {
    //        this.name = name;
    //    }
    //
    //    public void setDesc(String desc) {
    //        this.desc = desc;
    //    }
    
        public String getName() {
            return name;
        }
    
        public String getDesc() {
            return desc;
        }
    
        //3、在Season内部直接创建固定的对象
        //4、若使用静态属性会导致Season加载,若加上final,不会导致类加载
        public static final Season SPRING = new Season("Spring", "Warm");
        public static final Season SUMMER = new Season("Summer", "Hot");
        public static final Season AUTUMN = new Season("Autumn", "不舒服");
        public static final Season WINTER = new Season("Winter", "Warm");
    }
    

用关键字enum来实现枚举类

使用方法:

  • 1、使用关键字enum来代替class
  • 2、直接使用对象名(属性…)来创建对象相当于替代了public static final Season SPRING = new Season(“Spring”, “Warm”);
  • 3、若有多个对象,用,隔开
  • 4、若用enum实现枚举,要求将定义常量对象写在最前面

举例:

public class Enum02 {
    public static void main(String[] args) {
        System.out.println(Season.SPRING);
        System.out.println(Season.SUMMER);
        System.out.println(Season.AUTUMN);
        System.out.println(Season.WINTER);
    }
}

enum Season{

    SPRING("春天", "温暖"),SUMMER("夏天","热"),
    AUTUMN("秋天","凉爽"),WINTER("冬天","冷");
    private String name;//名字
    private String desc;//描述

    Season(String name, String desc) {
        this.name = name;
        this.desc = desc;
    }

    @Override
    public String toString() {
        return "Season{" +
                "name='" + name + '\'' +
                ", desc='" + desc + '\'' +
                '}';
    }
}

注意事项:

  • 当我们使用enum时,会默认继承enum类(用javap反编译得到结果如下)

    可以看出对象确实是public static final的

在这里插入图片描述

  • 使用时注意使用的是哪种构造器,如果使用的是无参构造器,则其实参列表和小括号都可以省略
  • 当枚举对象有多个时,要使用,分割,最后用分号结尾
  • 枚举对象一定要放在枚举类的行首

练习:

public class Exercise {
    public static void main(String[] args) {
        Gender boy = Gender.BOY;
        Gender boy2 = Gender.BOY;
        System.out.println(boy);
        //Gender中没有toString方法,因此会调用父类中的toString()方法,即Enum中的toString
        //可查看toString源码得知toString()方法返回的是name,即类名
        System.out.println(boy == boy2);
    }
}

//输出:
BOY
true
    
    

enum Gender{
    BOY, GIRL;
    //无属性,无构造器使用默认构造器,因此这种写法是正确的
}

练习二:(枚举与switch搭配使用)

public class Homework08 {
    public static void main(String[] args) {
        //枚举值与switch搭配使用
        Color green = Color.GREEN;
        green.show();
        switch (green){
            case YELLOW:
                System.out.println("匹配到...");
                break;
            default:
                System.out.println("无");
        }
    }
}

enum Color implements Beauty{
    RED(255,0,0),
    BLUE(0,0,255),
    BLACK(0,0,0),
    YELLOW(255,255,0),
    GREEN(0,255,0);
    private int redValue;
    private int greenValue;
    private int blueValue;

    private Color(int redValue, int greenValue, int blueValue) {
        this.redValue = redValue;
        this.greenValue = greenValue;
        this.blueValue = blueValue;
    }

    @Override
    public void show() {
        System.out.println("redValue:" + redValue
        + "\tgreenValue:" + greenValue
        + "\tblueValue:" + blueValue);
    }
}

interface Beauty{
    void show();
}

enum常用方法说明,因为继承了Enum类,我们可以使用Enum类相关的方法,Enum源码如下:

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");
    }
}
  • name方法(返回此枚举常量的名称)
  • ordinal方法(返回此枚举常量的序号)
  • values方法 Season.values(),返回一个此类中所有常量组成的数组
  • valueOf方法,将字符串转为枚举对象(字符串为枚举常量名,类似于Python字典),要求是字符串必须为已经有的常量名,否则会报异常
  • compareTo 比较两个枚举常量,按照编号比较,返回编号差值 调用对象编号-比较对象编号
    public class EnumMethod {
        public static void main(String[] args) {
            Season season = Season.AUTUMN;
            Season season1 = Season.AUTUMN;
            System.out.println(season.name());
            System.out.println(season.ordinal());
            Season[] values = Season.values();
            for(Season value: values){
                System.out.println(value);
            }
            Season season2 = Season.valueOf("SUMMER");
            System.out.println("season2="+season2);
            System.out.println(Season.WINTER.compareTo(Season.SPRING));
        }
    }
    //输出:
    AUTUMN
    2
    Season{name='春天', desc='温暖'}
    Season{name='夏天', desc='热'}
    Season{name='秋天', desc='凉爽'}
    Season{name='冬天', desc='冷'}
    season2=Season{name='夏天', desc='热'}
    3
    

实现细节:

  • 使用enum关键字后就不能再继承其他类了,因为enum会隐式继承Enum,而Java是单继承机制
  • 枚举类和普通类一样,可以实现接口 例子:
    public class EnumDetails {
        public static void main(String[] args) {
            Wants.CAT.cry();
        }
    }
    
    interface Animal{
        void cry();
    }
    
    enum Wants implements Animal{
        CAT,DOG,FISH,BIRD;
    
        @Override
        public void cry() {
            System.out.println("Cat");
        }
    }
    //输出:
    Cat
    

注解(Annotation)

@注解名 可以理解为有功能的注释Java SE中使用较少,Java EE中大量使用

三个基本注解:

  • @Override 重写父类方法,只能用于方法

    会检查是否构成了重写,若没构成重写,会报错
    打开源码会发现有一个注解@Target,这个注解是元注解,用于表示该注解是注解
    class Father{
        public void play(){
            System.out.println("Father");
        }
    }
    
    class Son extends Father{
        //加不加@Override都可以构成重写,但是加了会对是否重写了进行检查
        @Override
        public void play() {
            System.out.println("Son");
        }
    }
    
  • @Deprecated 用于表示某个程序元素(类或方法)已经过时(不推荐使用但是仍然可以使用),可以修饰方法、类、字段、包、参数等(可以做版本升级的过渡使用)

    public class AnnoTest {
        public static void main(String[] args) {
            A a = new A();
            a.play();
        }
    }
    
    @Deprecated
    class A{
        @Deprecated
        public void play(){
            System.out.println("A");
        }
    }
    

在这里插入图片描述

在这里插入图片描述

  • @SuppressWarnings 用于抑制编译器警告

    在这里插入图片描述

    抑制这个黄色的警告

在这里插入图片描述

作用域:方法、语句或者类上

元注解(了解即可,防止看源码的时候不知道这些注解是干什么的)

  • @Retention //指定注解的作用范围(编译时、运行时…)

  • @Target //指定注解在哪些地方可以使用

  • @Documented //指定该注解是否会在javadoc体现

  • @Inherited //子类会继承父类注解

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值