Java用自定义类实现枚举效果
Posted 学习笔记
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Java用自定义类实现枚举效果相关的知识,希望对你有一定的参考价值。
public class Season {
private Season() {}//使此类不能被new
public static final Season SPRING = new Season();
public static final Season SUMMER = new Season();
public static final Season FALL = new Season();
public static final Season WINTER = new Season();
}
public class Main {
public static void main(String[] args) {
Season s = Season.SPRING;
if(s==Season.SPRING){
System.out.println("春天");
}else if (s==Season.SUMMER){
System.out.println("夏天");
}else if (s==Season.FALL){
System.out.println("秋天");
}else if(s==Season.WINTER){
System.out.println("冬天");
}
}
}
在Java中使用枚举
public class Main {
public static void main(String[] args) {
Season s = Season.WINTER;
//打印枚举的名称 WINTRE
System.out.println(s.name());
//打印枚举的索引 3
System.out.println(s.ordinal());
}
public enum Season {
SPRING,SUMMER,FALL,WINTER
}
}
以上是关于Java用自定义类实现枚举效果的主要内容,如果未能解决你的问题,请参考以下文章