枚举类型

enum Color {
    RED, GREEN,BLUE ;
}
public class TestDemo {
    public static void main(String args[] ) {
        Color red  = Color.RED ;
        System.out.println(red) ;
    }
}

//作用:可以代替多例

enum Color {
    RED, GREEN,BLUE ;
}
public class TestDemo {
    public static void main(String args[] ) {
        for(Color c : Color.values()) {
            System.out.println(c.ordinal()+"-"+c.name()) ;
        }
    }
}

面试题:请解释enum和Enum的区别?
· enum是一个关键字,而Enum是一个抽象类;
· 使用enum定义一个枚举就相当于一个类继承了Enum这个抽象类。

代码改进:

enum Color { 
    RED("红色"), GREEN("绿色"),BLUE("蓝色") ;
    private String title ; 
    private Color (String title) {
        this.title = title  ;
    }
    public String toString () {
        return this.title ;
    }
}
public class TestDemo {
    public static void main(String args[] ) {
        for(Color c : Color.values()) {
            System.out.println(c) ; //直接输出对象调用toString()
        }
    }
}

枚举实现接口

interface Message{
    public String getTitle() ;
}
enum Color implements Message { 
    RED("红色"), GREEN("绿色"),BLUE("蓝色") ;
    private String title ;  //属性
    private Color (String title) {
        this.title = title  ;
    }
    public String toString () {
        return this.title ;
    }
    public String getTitle() {
        return this.title ;
    }
}
public class TestDemo {
    public static void main(String args[] ) {
        Message msg = Color.RED ;
            System.out.println(msg.getTitle()) ;
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容