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;
    
            }
        }
    
    }
    
    
  • 相关阅读:
    redis持久化,主从及数据备份
    验证redis的快照和AOF
    Erlang中日志管理
    erlang tcp发包速度测试
    树(234树插入查找显示)
    JDBC(初步试用)
    树(二叉树的插入删除查找遍历)
    哈希表(链地址法插入删除)
    哈希表-再哈希法插入删除
    哈希表-线性探测插入删除
  • 原文地址:https://www.cnblogs.com/thewindyz/p/14378655.html
Copyright © 2011-2022 走看看