zoukankan      html  css  js  c++  java
  • 使用枚举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();
            
        }

    输出:

  • 相关阅读:
    jQuery及javascript DOM创建节点(三)
    jQueryEasyUI Window的基本使用
    3.1、值类型
    手动依赖注入(二)
    3.1.2、字符类型
    不错不错
    我们应该讨论什么? 就面向对象的讨论所引发的一些思考
    保存个地址, 顺便问个问题~
    嗯嗯, 今天很高兴
    方法级AOP: 又一个补丁
  • 原文地址:https://www.cnblogs.com/nelson-hu/p/7902976.html
Copyright © 2011-2022 走看看