|NO.Z.00082|——————————|BigDataEnd|——|Java&特殊类.V10|——|Java.v10|枚举类|概念|自定义实现|

一、枚举类的概念和自定义实现
### --- 枚举的基本概念

~~~     ——>        一年中的所有季节:春季、夏季、秋季、冬季。
~~~     ——>        所有的性别:男、女。
~~~     ——>        键盘上的所有方向按键:向上、向下、向左、向右。
~~~     ——>        在日常生活中这些事物的取值只有明确的几个固定值,
~~~     ——>        此时描述这些事物的所有值都可以一一列举出来,而这个列举出来的类型就叫做枚举类型。
二、编程代码
package com.yanqi.task10;

/**
 * 编程实现所有方向的枚举,所有的方向:向上、向下、向左、向右
 */
public class Direction {
    private final String desc; // 用于描述方向字符串的成员变量

    // 2.声明本类类型的引用指向本类类型的对象
    public static final Direction UP = new Direction("向上");
    public static final Direction DOWN = new Direction("向下");
    public static final Direction LEFT = new Direction("向左");
    public static final Direction RIGHT = new Direction("向右");

    // 通过构造方法实现成员变量的初始化,更加灵活
    // 1.私有化构造方法,此时该构造方法只能在本类的内部使用
    private Direction(String desc) {
        this.desc = desc;
    }

    // 通过公有的get方法可以在本类的外部访问该类成员变量的数值
    public String getDesc() {
        return desc;
    }
}
三、编程代码
package com.yanqi.task10;

public class DirectionTest {

    public static void main(String[] args) {

        /*// 1.声明Direction类型的引用指向该类型的对象并打印特征
        Direction d1 = new Direction("向上");
        System.out.println("获取到的字符串是:" + d1.getDesc()); // 向上

        Direction d2 = new Direction("向下");
        System.out.println("获取到的字符串是:" + d2.getDesc()); // 向下

        Direction d3 = new Direction("向左");
        System.out.println("获取到的字符串是:" + d3.getDesc()); // 向左

        Direction d4 = new Direction("向右");
        System.out.println("获取到的字符串是:" + d4.getDesc()); // 向右

        System.out.println("-------------------------------------");
        Direction d5 = new Direction("向前");
        System.out.println("获取到的字符串是:" + d5.getDesc()); // 向前*/

        //Direction.UP = 2; Error:类型不匹配
        //Direction d2 = null;
        //Direction.UP = d2; Error: final关键字修饰
        Direction d1 = Direction.UP;
        System.out.println("获取到的方向是:" + d1.getDesc()); // 向上

        System.out.println("-------------------------------------");
        // 使用一下Java5开始的枚举类型
        DirectionEnum de = DirectionEnum.DOWN;
        System.out.println("获取到的方向是:" + de.getDesc()); // 向下
    }
}
四、编译打印
D:\JAVA\jdk-11.0.2\bin\java.exe "-javaagent:D:\IntelliJIDEA\IntelliJ IDEA 2019.3.3\lib\idea_rt.jar=54403:D:\IntelliJIDEA\IntelliJ IDEA 2019.3.3\bin" -Dfile.encoding=UTF-8 -classpath E:\NO.Z.10000——javaproject\NO.H.00001.javase\javase\out\production\javase com.yanqi.task10.DirectionTest
获取到的方向是:向上
-------------------------------------
获取到的方向是:向下

Process finished with exit code 0

 
 
 
 
 
 
 
 
 

Walter Savage Landor:strove with none,for none was worth my strife.Nature I loved and, next to Nature, Art:I warm'd both hands before the fire of life.It sinks, and I am ready to depart
                                                                                                                                                   ——W.S.Landor

 

posted on 2022-04-03 18:08  yanqi_vip  阅读(23)  评论(0)    收藏  举报

导航