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;
    
            }
        }
    
    }
    
    
  • 相关阅读:
    rabbimq连接问题处理
    svn小设置
    日志的乱码,以及数据库编码问题
    Intellij Idea 14 使用jetty-maven-plugin配置运行web工程
    心血来潮
    maven nexus 私服的搭建学习
    致成长——毕业一周年
    2015-7-2
    我的JQuery复习笔记之①——text(),html(),val()的区别
    【转】title与alt的区别
  • 原文地址:https://www.cnblogs.com/thewindyz/p/14378655.html
Copyright © 2011-2022 走看看