s-day12-枚举的基本定义
This commit is contained in:
@@ -0,0 +1,21 @@
|
|||||||
|
package com.inmind.enum03;
|
||||||
|
/*
|
||||||
|
enum是一种特殊的类
|
||||||
|
1.枚举类的第一行只能罗列一些名称,这些名称都是常量,并且每个常量都是枚举类的一个对象(枚举常量本质上是该枚举类型的实例,编译器会自动为它们添加 public static final 修饰符)
|
||||||
|
2.枚举类的构造器都是私有的,因此枚举类对外不能创建对象
|
||||||
|
3.枚举是最终类,不能被继承
|
||||||
|
4.枚举类中,第二行开始,可以定义枚举类的各种成员
|
||||||
|
5.编译器为枚举类新增了几个方法,并且枚举类都是继承java.lang.Enum类的,从enum类会继承一些方法
|
||||||
|
*/
|
||||||
|
public class Demo04 {
|
||||||
|
public static void main(String[] args) {
|
||||||
|
//创建枚举类型的变量
|
||||||
|
Light light1 = Light.red;
|
||||||
|
Light light2 = Light.yellow;
|
||||||
|
Light light3 = Light.green;
|
||||||
|
System.out.println(light1.getName());
|
||||||
|
System.out.println(light2.getName());
|
||||||
|
System.out.println(light3.getName());
|
||||||
|
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,25 @@
|
|||||||
|
package com.inmind.enum03;
|
||||||
|
|
||||||
|
public enum Light {
|
||||||
|
/*public static final*/ red("红灯"),yellow("黄灯"),green("绿灯");
|
||||||
|
private String name;
|
||||||
|
|
||||||
|
//枚举的构造方法
|
||||||
|
private Light(String name){
|
||||||
|
this.name = name;
|
||||||
|
}
|
||||||
|
|
||||||
|
private Light(){
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
//成员方法
|
||||||
|
public String getName() {
|
||||||
|
return name;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setName(String name) {
|
||||||
|
this.name = name;
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user