国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 學院 > 開發設計 > 正文

Java 1.5新特性Enum列舉的用法

2019-11-18 14:06:13
字體:
來源:轉載
供稿:網友

  Enum是enumeration(列舉)的簡寫形式,包含在java.lang包中。熟悉C, C++, C#, 或 Pascal人應該對列舉有所了解,先看個例子:

  public enum Season { winter, sPRing, summer, fall }

  一個enum是定義一組值的對象,它可以包括零個或多個值成員。它是屬于enum類型的,一個enum對象中不可有兩個或多個相同的屬性或值。在次之前的java程序員一般是 用接口的方法實現列舉的,如 :

  public interface Season {

  static winter = 0;

  static spring = 1; //etc……

  }

  引入了enum的java的列舉的編寫方便了許多,只須定義一個enum型的對象。enum對象的值都回自動獲得一個數字值,從0開始,依次遞增。看一個比較簡單的enum實現的例子:

  EnumDemo.java

  package net.javagarage.enums;

  /*

  We can loop over the values we put into the enum

  using the values() method.

  Note that the enum Seasons is compiled into a

  separate unit, called EnumDemo$Seasons.class

  */

  public class EnumDemo {

  /*declare the enum and add values to it. note that, like in C#, we don't use a ; to

  end this statement and we use commas to separate the values */

  private enum Seasons { winter, spring,

  summer, fall }

  //list the values

  public static void main(String[] args) {

  for (Seasons s : Seasons.values()){

  System.out.println(s);

  }

  }

  }運行上述代碼你回得到 以下結果:

  winter

  spring

  summer

  fall


 

  Enum的屬性調用:

  下面的代碼展示了調用enum對象的方法,這也是它通常的用法:

  package net.javagarage.enums;

  /*

  File: EnumSwitch.java

  Purpose: show how to switch against the values in an enum.

  */

  public class EnumSwitch {

  private enum Color { red, blue, green }

  //list the values

  public static void main(String[] args) {

  //refer to the qualified value

  doIt(Color.red);

  }

  /*note that you switch against the UNQUALIFIED name. that is, "case Color.red:" is a

  compiler error */

  private static void doIt(Color c){

  switch (c) {

  case red:

  System.out.println("value is " + Color.red);

  break;

  case green:

  System.out.println("value is " + Color.green);

  break;

  case blue:

  System.out.println("value is : " + Color.blue);

  break;

  default :

  System.out.println("default");

  }

  }


 

  為enums添加屬性和方法

  enums也可以象一般的類一樣添加方法和屬性,你可以為它添加靜態和非靜態的屬性或方法,這一切都象你在一般的類中做的那樣。

  package net.javagarage.enums;

  /*

  File: EnumDemo.java

  Purpose: show how to use an enum that also defines its own fields and methods

  */

  public class EnumWithMethods {

  //declare the enum and add values to it.

  public enum Season {

  winter, spring, summer, fall;



發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 唐海县| 海阳市| 麻栗坡县| 长海县| 水富县| 思茅市| 栖霞市| 三都| 霍邱县| 斗六市| 锡林浩特市| 九龙坡区| 邵阳县| 思南县| 砀山县| 南陵县| 岳阳市| 静安区| 兴安盟| 惠安县| 德化县| 高平市| 保定市| 盐山县| 绥江县| 富裕县| 五原县| 金川县| 和静县| 三都| 岳阳市| 常山县| 鄂州市| 佛山市| 灌阳县| 鄄城县| 马边| 白山市| 凤阳县| 寻甸| 四平市|