zoukankan      html  css  js  c++  java
  • java enum

    一、参考

    Java Enums

    二、enum

    2.1 定义

    constants: unchangeable variables, like final variables

    An enum is a special "class" that represents a group of constants

    2.2 创建

    To create an enum,

    (1) use the enum keyword (instead of class or interface),

    (2) separate the constants with a comma.

    (3) Note that they should be in uppercase letters

    2.3 获取

    You can access enum constants with the dot syntax

    Enum is short for "enumerations", which means "specifically listed".

    2.4 使用场景

    Enums are often used in switch statements to check for corresponding values

    The enum type has a values() method, which returns an array of all enum constants.

    This method is useful when you want to loop through the constants of an enum

    Use enums when you have values that you know aren't going to change, like month days, days, colors, deck of cards, etc.

    2.5 与 class 比较

    Difference between Enums and Classes

    (1) An enum can, just like a class, have attributes and methods.

    (2) The only difference is that enum constants are public, static and final (unchangeable - cannot be overridden).

    (3) An enum cannot be used to create objects, and it cannot extend other classes (but it can implement interfaces)

    2.6 示例

    package basic;
    
    public class EnumLearn {
    
        enum Level {
            LOW, MEDIUM, HIGH,
        }
    
        public static void main(String[] args) {
    
            // (1) 简单print
            printLevel();
            // (2) loop
            loopLevel();
            // (3) switch
            switchLevel();
    
        }
    
        // (1) 简单print
        public static void printLevel() {
            Level myVar = Level.MEDIUM;
            System.out.println("myVar: " + myVar);
        }
    
        // (2) loop
        public static void loopLevel() {
            for (Level myVar : Level.values()) {
                System.out.println(myVar);
            }
        }
    
        // (3) switch
        public static void switchLevel() {
            Level myVar = Level.MEDIUM;
    
            switch (myVar) {
    
                case LOW:
                    System.out.println("Low level");
                    break;
    
                case MEDIUM:
    
                    System.out.println("Medium level");
                    break;
    
                case HIGH:
                    System.out.println("High level");
                    break;
    
            }
        }
    
    }
    
    
  • 相关阅读:
    浮窗显示到毫秒时间的小工具 各大电商平台的时间
    非常不错的电脑截图软件介绍—截图加贴图。
    ​Everything 文件搜索神器 基于名称实时定位文件和目录
    THUPC2021初赛 & ICPC上海站游记
    旧题重做
    常用思想方法——数学期望篇
    vim 常用操作技巧
    生物制图软件——CirCos在Linux服务器上安装步骤:
    vue-element-admin 改造
    vue
  • 原文地址:https://www.cnblogs.com/thewindyz/p/14378655.html
Copyright © 2011-2022 走看看