首页 > 其他分享 >枚举的使用与详解

枚举的使用与详解

时间:2022-10-05 19:45:00浏览次数:58  
标签:String Season System 枚举 详解 使用 println public

一:枚举的引入

【1】数学:枚举法:
  1<x<4
  2<y<5
  求x+y=6

  枚举法:一枚一枚的列举出来。前提:有限,确定

【2】在java中,类的对象是有限个,确定的。这个类我们可以定义为枚举类。
  举例:
    星期:一二三四五六日
    性别:男女
    季节:春夏秋冬

【3】自定义枚举类:(JDK1.5之前自定义枚举类)

package com.mingyuanyun.enumdemo;

/**
 * @Auther: wty01
 * @Date: 2022/10/5
 * @Description: com.mingyuanyun.enumdemo
 */

/**
 * 定义枚举类:季节
 */
public class Season {
    private final String seasonName;  //季节名称
    private final String seasonDesc;  //季节描述

    //利用构造器对属性进行赋值操作:
    //构造器私有化,外界不能调用这个构造器,只能Season内部自己调用
    private Season(String seasonName, String seasonDesc) {
        this.seasonName = seasonName;
        this.seasonDesc = seasonDesc;
    }

    //创建枚举类的有限的确定的对象
    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 getSeasonName() {
        return seasonName;
    }

    public String getSeasonDesc() {
        return seasonDesc;
    }

    //toString();
    @Override
    public String toString() {
        return "Season{" +
                "seasonName='" + seasonName + '\'' +
                ", seasonDesc='" + seasonDesc + '\'' +
                '}';
    }
}

  测试类:TestSeason

package com.mingyuanyun.enumdemo;

/**
 * @Auther: wty01
 * @Date: 2022/10/5
 * @Description: com.mingyuanyun.enumdemo
 */
public class TestSeason {
    //这是一个main方法,是程序的入口:
    public static void main(String[] args) {
        Season summer = Season.SUMMER;
        System.out.println(summer/*.toString()*/);
        System.out.println(summer.getSeasonName());
    }
package com.mingyuanyun.enumdemo2;

/**
 * @Auther: wty01
 * @Date: 2022/10/5
 * @Description: com.mingyuanyun.enumdemo
 */ 

二、JDK1.5以后使用enum关键字创建枚举类:

package com.mingyuanyun.enumdemo2;

/**
 * @Auther: wty01
 * @Date: 2022/10/5
 * @Description: com.mingyuanyun.enumdemo
 */

/**
 * 定义枚举:季节
 */
public enum Season {
    //创建枚举类的有限的确定的对象---->enum枚举要求对象(常量)必须放在最开始的位置上
    SPRING("春天", "春暖花开"),
    SUMMER("夏天", "烈日炎炎"),
    AUTUMN("秋天", "硕果累累"),
    WINTER("冬天", "冰天雪地");
    //属性
    private final String seasonName;  //季节名称
    private final String seasonDesc;  //季节描述

    private Season(String seasonName, String seasonDesc) {
        this.seasonName = seasonName;
        this.seasonDesc = seasonDesc;
    }

    public String getSeasonName() {
        return seasonName;
    }

    public String getSeasonDesc() {
        return seasonDesc;
    }

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

(1)使用枚举类:

package com.mingyuanyun.enumdemo2;

/**
 * @Auther: wty01
 * @Date: 2022/10/5
 * @Description: com.mingyuanyun.enumdemo2
 */
public class TestSeason {
    public static void main(String[] args) {
        Season winter = Season.WINTER;
        System.out.println(winter);
        //enum关键字对应的枚举类的上层父类是 :java.lang.Enum
        //但是我们自定义的枚举类的上层父类:Object
        System.out.println(Season.class.getSuperclass().getName());//java.lang.Enum
    }
}

 (2)在源码中经常看到别人定义的枚举类形态:

package com.mingyuanyun.enumdemo3;

/**
 * @Auther: wty01
 * @Date: 2022/10/5
 * @Description: com.mingyuanyun.enumdemo3
 */
public enum Season {
    SPRING,
    SUMMER,
    AUTUMN,
    WINTER
}

为什么这么简单:因为这个枚举类底层没有属性,属性,构造器,toString,get方法都删掉不写了,然后案例来说应该写为:SPRING()   现在连()可以省略 就变成  SPRING
看到的形态就剩:常量名(对象名)

案例:
Thread中的枚举类:State

public enum State {
        /**
         * Thread state for a thread which has not yet started.
         */
        NEW,
        /**
         * Thread state for a runnable thread.  A thread in the runnable
         * state is executing in the Java virtual machine but it may
         * be waiting for other resources from the operating system
         * such as processor.
         */
        RUNNABLE,
        /**
         * Thread state for a thread blocked waiting for a monitor lock.
         * A thread in the blocked state is waiting for a monitor lock
         * to enter a synchronized block/method or
         * reenter a synchronized block/method after calling
         * {@link Object#wait() Object.wait}.
         */
        BLOCKED,
        /**
         * Thread state for a waiting thread.
         * A thread is in the waiting state due to calling one of the
         * following methods:
         * <ul>
         *   <li>{@link Object#wait() Object.wait} with no timeout</li>
         *   <li>{@link #join() Thread.join} with no timeout</li>
         *   <li>{@link LockSupport#park() LockSupport.park}</li>
         * </ul>
         *
         * <p>A thread in the waiting state is waiting for another thread to
         * perform a particular action.
         *
         * For example, a thread that has called <tt>Object.wait()</tt>
         * on an object is waiting for another thread to call
         * <tt>Object.notify()</tt> or <tt>Object.notifyAll()</tt> on
         * that object. A thread that has called <tt>Thread.join()</tt>
         * is waiting for a specified thread to terminate.
         */
        WAITING,
        /**
         * Thread state for a waiting thread with a specified waiting time.
         * A thread is in the timed waiting state due to calling one of
         * the following methods with a specified positive waiting time:
         * <ul>
         *   <li>{@link #sleep Thread.sleep}</li>
         *   <li>{@link Object#wait(long) Object.wait} with timeout</li>
         *   <li>{@link #join(long) Thread.join} with timeout</li>
         *   <li>{@link LockSupport#parkNanos LockSupport.parkNanos}</li>
         *   <li>{@link LockSupport#parkUntil LockSupport.parkUntil}</li>
         * </ul>
         */
        TIMED_WAITING,
        /**
         * Thread state for a terminated thread.
         * The thread has completed execution.
         */
        TERMINATED;

(3)Enum类的常用方法:

package com.mingyuanyun.enumdemo3;

/**
 * @Auther: wty01
 * @Date: 2022/10/5
 * @Description: com.mingyuanyun.enumdemo3
 */
public class TestSeason {
    //这是一个main方法,是程序的入口:
    public static void main(String[] args) {
        //用enum关键字创建的Season枚举类上面的父类是:java.lang.Enum,常用方法子类Season可以直接拿过来使用:
        //toString();--->获取对象的名字
        Season autumn = Season.AUTUMN;
        System.out.println(autumn/*.toString()*/);//AUTUMN
        System.out.println("--------------------");
        //values:返回枚举类对象的数组
        Season[] values = Season.values();
        for (Season s : values) {
            System.out.println(s/*.toString()*/);
        }
        System.out.println("--------------------");
        //valueOf:通过对象名字获取这个枚举对象
        //注意:对象的名字必须传正确,否则抛出异常
        Season autumn1 = Season.valueOf("AUTUMN");
        System.out.println(autumn1);
    }
}

(4)枚举类实现接口:

  1.定义一个接口:

public interface TestInterface {
    void show();
}

  2.枚举类实现接口,并且重写show方法:

public enum Season implements TestInterface {
    SPRING,
    SUMMER,
    AUTUMN,
    WINTER;
    @Override
    public void show() {
        System.out.println("这是Season....");
    }
}

  测试:

public class Test {
    //这是一个main方法,是程序的入口:
    public static void main(String[] args) {
        Season autumn = Season.AUTUMN;
        autumn.show();
        Season summer = Season.SUMMER;
        summer.show();
    }
}

上面发现所有的枚举对象,调用这个show方法的时候走的都是同一个方法,结果都一样:

但是现在我想要:不同的对象  调用的show方法也不同:

package com.mingyuanyun.enumdemo4
import java.sql.SQLOutput;
public enum Season implements TestInterface {
    SPRING{
        @Override
        public void show() {
            System.out.println("这是春天。。。");
        }
    },
    SUMMER{
        @Override
        public void show() {
            System.out.println("这是夏天。。");
        }
    },
    AUTUMN{
        @Override
        public void show() {
            System.out.println("这是秋天");
        }
    },
    WINTER{
        @Override
        public void show() {
            System.out.println("这是冬天");
        }
    };
    /*@Override
    public void show() {
        System.out.println("这是Season....");
    }*/
}

测试类:

public class Test {
    //这是一个main方法,是程序的入口:
    public static void main(String[] args) {
        Season autumn = Season.AUTUMN;
        autumn.show();
        Season summer = Season.SUMMER;
        summer.show();
    }
}

(5)实际应用

package com.mingyuanyun.enumdemo5;
/**
 * @author : msb-zhaoss
 */
public class Person {
    //属性:
    private int age;
    private String name;
    private Gender sex;
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public Gender getSex() {
        return sex;
    }
    public void setSex(Gender sex) {
        this.sex = sex;
    }
    @Override
    public String toString() {
        return "Person{" +
                "age=" + age +
                ", name='" + name + '\'' +
                ", sex='" + sex + '\'' +
                '}';
    }
}
public enum Gender {
    男,
    女;
}
public class Test {
    //这是一个main方法,是程序的入口:
    public static void main(String[] args) {
        Person p = new Person();
        p.setAge(19);
        p.setName("lili");
        p.setSex(Gender.男);//传入枚举类Gender的对象:-->在入口处对参数进行了限制
        System.out.println(p);
    }
}

 

还可以通过枚举结合switch处理:

public class Test02 {
    //这是一个main方法,是程序的入口:
    public static void main(String[] args) {
        Gender sex = Gender.男;
        //switch后面的()中可以传入枚举类型
        //switch后面的():int,short,byte,char,String ,枚举
        switch (sex){
            case 女:
                System.out.println("是个女孩");
                break;
            case 男:
                System.out.println("是个男孩");
                break;
        }
    }
}

 

标签:String,Season,System,枚举,详解,使用,println,public
From: https://www.cnblogs.com/wtyhbh/p/16756202.html

相关文章

  • 使用mock.js来模拟后台数据的方案
    如何在项目中引入mockjs,从而实现脱离后端数据,前端做假数据来独立开发业务逻辑。一.安装依赖npmimockjs--save-dev二.使用mock按照业务模块建立一个文件来写模拟......
  • this关键字的使用
    1.this.属性=同名实参此时this代表这个对象2.this(形参列表)此时this调用构造器3.this.方法名访问该类里的另一个方法或实例变量 ......
  • Windows下使用Visual Code编写并编译基于C的Python插件
    环境本地Windows10,VisualCode,Pyhton3.10Python的安装路径d:/develop/python/Python3101、C代码fputsmodule.c#include<Python.h>//https://realpython.com/bui......
  • vue(8)v-model与JavaScript中array对象的配合使用
    序实现了之前代码的删除功能,并加入了对于复选框的全选,全不选,反选等功能示例代码展开查看<!DOCTYPEhtml><html> <head> <meta......
  • 标记未使用的列
    如果您担心从大表中的所有行中删除列数据所需的时间长度,您可以使用该ALTERTABLE...SETUNUSED语句。该语句将一个或多个列标记为未使用,但实际上并未删除目标列数据或恢复......
  • 11_使用SDL播放WAV
    使用命令播放WAV对于WAV文件来说,可以直接使用ffplay命令播放,而且不用像PCM那样增加额外的参数。因为WAV的文件头中已经包含了相关的音频参数信息。ffplayin.wav接下来......
  • 746.min-cost-climbing-stairs 使用最小花费爬楼梯
    题目描述746.使用最小花费爬楼梯解题思路相当于爬楼梯的进阶版,递推关系变复杂了一些,但本质没有变。\(a_n=min(a_{n-1}+cost[i-1],a_{n-2}+cost[i-2])\)......
  • AcWing1362 健康的荷斯坦奶牛(二进制枚举)
    原题链接思路:二进制枚举因为数据量很小,数据只有25和15,因此二进制枚举妥妥的需要注意的是题目中要求下标从1开始,后面记录的时候如果开始是从0开始的记得+1小tipsc++......
  • Vue2 下 Echarts的使用
    Vue2下Echarts的使用1、安装组件npminstallechartsvue-echarts--save2、使用2.1、配置为全局组件方式全局配置为公有组件//main.jsimport"echarts"import......
  • JavaScript中的Promise详解
    我们了解Promise之前先了解一下什么是异步,因为Promise是用来处理异步操作的一、什么是异步异步(Asynchronous,async)是与同步(Synchronous,sync)相对的概念。总所周知,Jav......