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;
    
            }
        }
    
    }
    
    
  • 相关阅读:
    纯CSS垂直居中的四种解决方案
    UTF-8 UTF-16 UTF-32 最根本的区别?
    js中==和===区别
    关于端口的定义, 为什么要有端口
    变量命名规范
    使用枚举enum
    js中, 用变量或对象作为if或其他条件的表达式
    使用jquery-panzoom来实现图片或元素的放大缩小
    使用mescroll来实现移动端页面上拉刷新, 下拉加载更多功能
    angularjs常用事件
  • 原文地址:https://www.cnblogs.com/thewindyz/p/14378655.html
Copyright © 2011-2022 走看看