快速业务通道

Java 1.5新特性Enum的用法 - 编程入门网

作者 佚名技术 来源 NET编程 浏览 发布时间 2012-06-21

Java 1.5新特性Enum的用法

时间:2011-01-02 craboy

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

Java 1.5新特性Enum的用法(2)

时间:2011-01-02 craboy

Enum的属性调用:

下面的代码展示了调用enum对象的方法,这也是它通常的用法:

package net.javagarage.enums;/*File: EnumSwitch.javaPurpose: show how to switch against the values in an enum.*/public class EnumSwitch {private enum Color { red, blue, green }//list the valuespublic static void main(String[] args) {//refer to the qualified valuedoIt(Color.red);}/*note that you switch against the UNQUALIFIED name. that is, "case Color.red:" is acompiler 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.javaPurpose: 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;private final static String location = "Phoenix";public static Season getBest(){if (location.equals("Phoenix"))return winter;elsereturn summer;}public static void main(String[] args) {System.out.println(Season.getBest());}}

就是这么的简单.但是有一点是需要注意的,那就是enums的值列表必须紧跟在enum声明,不然编译时将会出错.

Java 1.5新特性Enum的用法(3)

时间:2011-01-02 craboy

Enums构造函数:

和类

凌众科技专业提供服务器租用、服务器托管、企业邮局、虚拟主机等服务,公司网站:http://www.lingzhong.cn 为了给广大客户了解更多的技术信息,本技术文章收集来源于网络,凌众科技尊重文章作者的版权,如果有涉及你的版权有必要删除你的文章,请和我们联系。以上信息与文章正文是不可分割的一部分,如果您要转载本文章,请保留以上信息,谢谢!

分享到: 更多

Copyright ©1999-2011 厦门凌众科技有限公司 厦门优通互联科技开发有限公司 All rights reserved

地址(ADD):厦门软件园二期望海路63号701E(东南融通旁) 邮编(ZIP):361008

电话:0592-5908028 传真:0592-5908039 咨询信箱:web@lingzhong.cn 咨询OICQ:173723134

《中华人民共和国增值电信业务经营许可证》闽B2-20100024  ICP备案:闽ICP备05037997号