A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

//枚举就相当于一个类,其中也有定义的构造方法、成员变量、普通方法和抽象法。
package cho1_gaoxinjishu;
//创建java类实现枚举。
public class WeekDay1 {
private WeekDay1(){} //私有构造方法,以免出现重复。

//设置常量,星期一二三四五六日。
public final static WeekDay1 SUN =new WeekDay1();
public final static WeekDay1 MON =new WeekDay1();
public final static WeekDay1 TUE =new WeekDay1();
public final static WeekDay1 WED =new WeekDay1();
public final static WeekDay1 THU =new WeekDay1();
public final static WeekDay1 FIR =new WeekDay1();
public final static WeekDay1 SAT =new WeekDay1();
//定义一个方法
public WeekDay1 nextDay(){
  if (this==SUN) {
   return MON;
  }else if(this==MON){
   return TUE;
  }else if(this==TUE){
   return WED;
  }else if(this==WED){
   return THU;
  }else if(this==THU){
   return FIR;
  }else if(this==FIR) {
   return SAT;
  }else {
   return SUN;
  }
}
public String toString(){
  return this==SUN?"SUN":"MON";
  
}
}
-----------------------------------------------------------
package cho1_gaoxinjishu;
public class EnumTest {
public static void main(String[] args) {
  // TODO Auto-generated method stub
  WeekDay1 weekDay =WeekDay1.MON;
  System.out.println(weekDay.nextDay());
  
  WeekDay weekDay2=WeekDay.FRI;
  System.out.println(weekDay2);
  //枚举的基本应用(方法)
  System.out.println(weekDay2.name());
  System.out.println(weekDay2.ordinal());
  System.out.println(WeekDay.valueOf("SUN"));
  System.out.println(WeekDay.values().length);
  
  }
public enum WeekDay{
  
  SUN,MON,TUE,WED,THU,FRI,SAT;
  
  //枚举的构造方法;
  private WeekDay(){System.out.println("frist");}
  private WeekDay(int day){System.out.println("second");};
}

//抽象内部内的、带方法的枚举。
public enum TrafficLamp{
  RED(30){
   public  TrafficLamp nextLamp(){
    return GREEN;
   }
  },
  GREEN(40){
   public  TrafficLamp nextLamp(){
    return YELLOW;
   }
   
  },
  YELLOW(5){
   public  TrafficLamp nextLamp(){
    return RED;
   }
  };
  public abstract TrafficLamp nextLamp();
  
  private int time;
  private TrafficLamp(int time)//构造方法,参数为时间
  {
   this.time=time;
  }
}
}

0 个回复

您需要登录后才可以回帖 登录 | 加入黑马