Enum列举的用法

1. Enums构造函数:
package net.javagarage.enums;

  public class EnumConstructor {

  public static void main(String[] a) {

  //call our enum using the values method

  for (Temp t : Temp.values())

  System.out.println(t + " is : " + t.getValue());

  }

  //make the enum

  public enum Temp {

  absoluteZero(-459), freezing(32),

  boiling(212), paperBurns(451);

  //constructor here

  Temp(int value) {

  this.value = value;

  }

  //regular field?but make it final,

  //since that is the point, to make constants

  private final int value;

  //regular get method

  public int getValue() {

  return value;

  }

  }

  }

输出结果是:

  absoluteZero is : -459

  freezing is : 32

  boiling is : 212

  paperBurns is : 451

2.为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;

  private final static String location = "Phoenix";

  public static Season getBest(){

  if (location.equals("Phoenix"))

  return winter;

  else

  return summer;

  }

  public static void main(String[] args) {

  System.out.println(Season.getBest());

  }

  }


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

3.Enum的属性调用:

  下面的代码展示了调用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");

  }

  }

4.一个比较简单的enum实现的例子
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
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值