• 使用枚举enum


    枚举可以把常量按照类别组织起来, 并且提供了构造方法和其他访问方法

    用法:

    package com.nel.testPro.useage.use_enum;
    
    public enum Color implements Behaviour{
        
        RED, YELLOW, BLUE, PINK("pink", 3); // 使用枚举, 可以将常量分类, 而且能提供比操作常量跟更多的方法
        
        // 自定义属性
        private String name;
        
        private Integer index;
        
        public String getName() {
            return name;
        }
    
        public void setName(String name) {
            this.name = name;
        }
    
        public Integer getIndex() {
            return index;
        }
    
        public void setIndex(Integer index) {
            this.index = index;
        }
    
        Color () {
            
        }
    
        // 自定义构造方法
        Color(String name, Integer index) {
            this.name = name;
            this.index = index;
        } 
        
        // 普通方法
        public static String getName(Integer index) {
            
            for (Color c : Color.values()) {
                if (c.getIndex() == index) {
                    return c.getName();
                }
            }
            return "not found";
        } 
        
        // 覆盖toString
        @Override
        public String toString() {
            return "this is " + this.name;
        }
      
        
       // 可以实现接口, 扩展其方法 @Override
    public void say() { System.out.println("say " + this.getName()); } }

    测试:

        public static void main(String[] args) {
            
            Color color = Color.RED;
            
            switch(color) {
            case RED:
                System.out.println("red");
                break;
            case BLUE:
                System.out.println("blue");
                break;
            case YELLOW:
                System.out.println("yellow");
                break;
            case PINK:
                System.out.println("pink");
            }
            
            //
            System.out.println(Color.getName(3));
            
            //
            System.out.println(Color.valueOf("PINK"));
            
            // 
            System.out.println(Color.valueOf(Color.class, "BLUE"));
            
            //
            Color.PINK.say();
            
        }

    输出:

  • 相关阅读:
    收藏一些常用的methods
    判断DOM是否全屏及相关API
    原生post 协议提交文件流 至OSS服务器
    vue 嵌套路由,router-link-active的问题
    关于JAVA变量,数据类型,基本数据类型之间的转换和对象型的基本数据类型
    关于循环语法
    java环境变量的设置
    java的运行机制, JVM
    2-ser2003系统封装实验报告
    1-ser2008系统封装实验报告
  • 原文地址:https://www.cnblogs.com/nelson-hu/p/7902976.html
Copyright © 2020-2023  润新知