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()) ;
}
}