码迷,mamicode.com
首页 > 其他好文 > 详细

枚举 定义其他结构

时间:2016-01-30 18:04:06      阅读:194      评论:0      收藏:0      [点我收藏+]

标签:

枚举是多例设计

要求构造方法私有化

枚举中定义的构造方法不能用public

枚举对象必须放在首行,随后才可以定义属性,构造方法,普通方法

 

package cn;
enum Color{        //定义好了枚举类
    RED("红色") ,GREEN ("绿色"),BLUE("蓝色") ;        //枚举对象dingyi8在最上面
    private String title ;    //属性
    private Color(String title){        //  私有
        this.title = title ;
    }
    public String toString (){
        return this.title ;
    }
}
public class Test {

    public static void main(String[] args) {
        for(Color c : Color.values()){
            System.out.println(c.ordinal()  + " "  + c) ;
        }
    }    
}

 

 

枚举实现接口

interface Message {
    public String getTitle() ;
}
enum Color implements Message{        //定义好了枚举类
    RED("红色") ,GREEN ("绿色"),BLUE("蓝色") ;        //枚举对象dingyi8在最上面
    private String title ;    //属性
    private Color(String title){        //  私有
        this.title = title ;
    }
    public String getTitle(){
        return this.title  ;
    }
}
public class Test {

    public static void main(String[] args) {
        Message msg = Color.RED ;
        System.out.println(msg.getTitle());
    }    
}

 

在每一个对象后面使用匿名内部类的形势实现方法

不写了。。

 

实际作用:

1.switch中

enum Color{
    RED , GREEN , BLUE ;
}
public class Test {

    public static void main(String[] args) {
        Color c = Color.RED ;
        switch(c){
        case RED:
            System.out.println("This is RED") ;
            break ;
        case GREEN:
            System.out.println("This is Green");
            break;
        case BLUE:
            System.out.println("This is BLUE");
            break;
        }
    }    
}

 

 

试图使用emnu

技术分享

 

枚举属于多例的设计模式,想用就用,不想用就不用。

 

枚举 定义其他结构

标签:

原文地址:http://www.cnblogs.com/da-peng/p/5171089.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!