码迷,mamicode.com
首页 > 编程语言 > 详细

Java用自定义类实现枚举效果

时间:2020-04-08 22:54:14      阅读:132      评论:0      收藏:0      [点我收藏+]

标签:定义类   不能   枚举   ring   private   string   ati   使用   打印   

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用自定义类实现枚举效果

标签:定义类   不能   枚举   ring   private   string   ati   使用   打印   

原文地址:https://www.cnblogs.com/xl4ng/p/12663078.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!