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;
    
            }
        }
    
    }
    
    
  • 相关阅读:
    lvs_基础理论
    iptables_表和链(Traversing of tables and chains)
    题解-【集训队作业2018】Simple Tree
    题解-CF559C
    题解-[Violet]天使玩偶/SJY摆棋子
    题解-[POI2014]PRZ-Criminals
    题解-CF961G
    题解-CF1392H
    WorldCreator基础流程
    gstreamer-vaapi 之 README
  • 原文地址:https://www.cnblogs.com/thewindyz/p/14378655.html
Copyright © 2011-2022 走看看