枚举 定义其他结构

枚举是多例设计

要求构造方法私有化

枚举中定义的构造方法不能用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

 

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

 

转载于:https://www.cnblogs.com/da-peng/p/5171089.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值