在枚举类(Enum)中使用方法

在枚举类(Enum)中使用方法

源码案例

java.util.concurrent.TimeUnit

Demo

package factory.enumdemo;

public enum  CommonEnum {

    SECOND {
        @Override
        protected String showTime(Long time) {
            return time + "秒";
        }
    },
    MINUTE {
        @Override
        protected String showTime(Long time) {
            return time + "分";
        }
    },
    HOUR {
        @Override
        protected String showTime(Long time) {
            return time + "时";
        }
    };
    // Enum中的方法在Enum中可以重写
    protected String showTime(Long time) {
        return "";
    }
    public void  print(Long time) {
        String msg = showTime(time);
        System.out.println(msg);
    }
}

调用 :

public static void main(String[] args) {
    CommonEnum.SECOND.print(10L);
    CommonEnum.MINUTE.print(10L);
    CommonEnum.HOUR.print(10L);
}
发布了78 篇原创文章 · 获赞 58 · 访问量 3万+

猜你喜欢

转载自blog.csdn.net/qq122516902/article/details/89446593