标签:
package com.btp.t4; /* * 一.枚举类 * 1.如何自定义枚举类 * 2.如何使用enum关键字定义枚举类 * >常用的方法:values(),valueOf(String name) * >如何让枚举类实现接口:让不同的枚举类对象调用被重写的抽象方法,执行的效果不同。(相当于让每个对象重写抽象方法) */ public class TestSeason { public static void main(String[] args){ Season spring=Season.SPRING; System.out.println(spring); spring.show(); System.out.println(spring.getSeasonDesc()); //1.values() Season1[] season=Season1.values(); for(Object obj:season) { System.out.println(obj); } System.out.println(); //2.valueOf(String name):要求传入的形参是枚举类对象的名字,否则报异常 String str="SPRING"; Season1 sea=Season1.valueOf(str); System.out.println(sea); System.out.println(); sea.show(); System.out.println(); //Thread类的内部类State是一个枚举类 Thread.State[] states=Thread.State.values(); for(Object obj:states) { System.out.println(obj); } } } //自定义枚举类:如果只有一个对象,则是单例模式 class Season{ //1.提供类的属性,声明为private final private final String seasonName; private final String seasonDesc; //2.声明为final的属性,在私有化构造器中初始化 private Season(String seasonName,String seasonDesc){ this.seasonName=seasonName; this.seasonDesc=seasonDesc; } //3.通过公共方法调用 public String getSeasonName() { return seasonName; } public String getSeasonDesc() { return seasonDesc; } //4.创建枚举类的对象:将类的对象声明为public static final public static final Season SPRING=new Season("spring","春暖花开"); public static final Season SUMMER=new Season("summer","夏日炎炎"); public static final Season AUTUMN=new Season("autumn","秋高气爽"); public static final Season WINTER=new Season("winter","白雪皑皑"); @Override public String toString() { return "Season [seasonName=" + seasonName + ", seasonDesc=" + seasonDesc + "]"; } public void show(){ System.out.println("这是一个"+this.getSeasonName()+"季节!"); } } //接口info interface info{ void show(); } //用enum关键字定义枚举类 enum Season1 implements info{ //成员要写在最前面 //让不同的枚举类对象调用被重写的抽象方法,执行的效果不同。(相当于让每个对象重写抽象方法) SPRING("spring","春暖花开"){ public void show(){ System.out.println("春天在哪里?"); } }, SUMMER("summer","夏日炎炎"){ public void show(){ System.out.println("生如夏花"); } }, AUTUMN("autumn","秋高气爽"){ public void show(){ System.out.println("秋天是分手的季节"); } }, WINTER("winter","白雪皑皑"){ public void show(){ System.out.println("冬天里的一把火火"); } }; private final String seasonName; private final String seasonDesc; private Season1(String seasonName,String seasonDesc){ this.seasonName=seasonName; this.seasonDesc=seasonDesc; } @Override public String toString() { return "Season [seasonName=" + seasonName + ", seasonDesc=" + seasonDesc + "]"; } // public void show() { // // TODO 自动生成的方法存根 // System.out.println("这是一个季节!"); // } }
标签:
原文地址:http://www.cnblogs.com/a842297171/p/5170344.html