实现带有抽象方法的枚举

枚举的进一步深入,实现带有抽象方法的枚举,以交通灯为例,代码如下:

package com.jemsn.weekday;

public class test {

	public static void main(String[] args) {
		TrafficLamp red=TrafficLamp.Red;
		System.out.println(red.NextLamp());
		System.out.println("this time is "+red.Time);
	}

	 public enum TrafficLamp{
		 Red(30){ 
			public TrafficLamp NextLamp() {				 
				return GREEN; 
			}			 
		 },
		 GREEN(45){ 
			public TrafficLamp NextLamp() {
			return YELLOW;
			}			 
		 },
		 YELLOW(5){ 
			public TrafficLamp NextLamp() {
				return Red;
			}			 
		 };
		 //抽象方法
		 public abstract TrafficLamp NextLamp();
		 private int Time;
		  
		 //枚举的有参构造函数
		 private TrafficLamp(int time) {
			this.Time=time;			
		}
	 }
}


输出的结果如下:

-------------------------------------------------------------------------------------------------

GREEN
this time is 30
-------------------------------------------------------------------------------------------------

上面的枚举TrafficLamp里实现了红 绿 黄 三种交通信号灯,并且用实现抽象方法来实现NextLamp下一个灯!个人感觉挺强打的!

你可能感兴趣的:(String,Class,交通)