使用枚举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();
        
    }

输出:

 

posted @ 2017-11-27 10:31  果感  阅读(262)  评论(0编辑  收藏  举报