本帖最后由 a6511631 于 2014-7-28 12:31 编辑
我建了一个class定义了一个抽象类TrafficLamp想模拟交通灯枚举TrafficLight。但是有个地方卡住了,不知道怎么模拟!求大神。。。附上抽象类的代码:- package com.itheima.day01;
- public abstract class TrafficLamp {
- // int second;
- private TrafficLamp(){}
- public static TrafficLamp Red = new TrafficLamp(){
- @Override
- public TrafficLamp nextLamp() {
- // TODO Auto-generated method stub
- return Green;
- }
- @Override
- public String toString() {
- // TODO Auto-generated method stub
- return "Red";
- }
- };
- public static TrafficLamp Green = new TrafficLamp(){
- int second = 30;
- @Override
- public TrafficLamp nextLamp() {
- // TODO Auto-generated method stub
- return Yellow;
- }
- @Override
- public String toString() {
- // TODO Auto-generated method stub
- return "Green";
- }
- };
- public static TrafficLamp Yellow = new TrafficLamp(){
- @Override
- public TrafficLamp nextLamp() {
- // TODO Auto-generated method stub
- return Red;
- }
- @Override
- public String toString() {
- // TODO Auto-generated method stub
- return "Yellow";
- }
-
- };
- public abstract TrafficLamp nextLamp();
- public abstract String toString();
-
- }
复制代码
再附上调用该抽象类及枚举TrafficLight的代码:
- package com.itheima.day01;
- public class EnumTest {
- public static void main(String[] args){
- /*TrafficLight tl = TrafficLight.Green;
- System.out.println(tl.toString());
- System.out.println(tl.nextLamp());
- System.out.println(tl.second);*/
- TrafficLamp tl = TrafficLamp.Green;
- System.out.println(tl.nextLamp().toString());
- System.out.println(tl.toString());
- //System.out.println(tl.second);
- //在这个抽象类TrafficLamp中如何像枚举那样使用tl.second得到每个灯的second呢?
- }
- public enum TrafficLight{
- Red(30){
- public TrafficLight nextLamp(){
- return Green;
- }
- }
- ,Green(35){
- public TrafficLight nextLamp(){
- return Yellow;
- }
- }
- ,Yellow(5){
- public TrafficLight nextLamp(){
- return Red;
- }
- };
- public abstract TrafficLight nextLamp();
- private int second;
- private TrafficLight(int second){
- this.second = second;
- }
- }
- }
复制代码
问题就是,在枚举TrafficLight中定义了每个灯的亮灯时间second,在调用时可以这样调用:TrafficLight.Grenn.second。
那么,在抽象类TrafficLamp中怎么写才可以也像这样的格式进行调用呢?如:TrafficLamp.Grenn.second。
|
|