java枚举和switch案例

来源:互联网 发布:广联达预算软件购买 编辑:程序博客网 时间:2024/06/04 18:19
 

package com;

interface Constants { // 将常量放置在接口中
 public static final int Enum_A = 1;
 public static final int Enum_B = 12;
}

public class Sample {
 enum Constants2 { // 将常量放置在枚举类型中
  Enum_A, Enum_B
 }
 
 // 使用接口定义常量
 public static void doit(int c) { // 定义一个方法,这里的参数为int型
  switch (c) { // 根据常量的值做不同操作
   case Constants.Enum_A:
    System.out.println("doit() Enum_A");
    break;
   case Constants.Enum_B:
    System.out.println("doit() Enum_B");
    break;
  }
 }
 // 定义一个方法,这里的参数为枚举类型对象
 public static void doit2(Constants2 c) {
  switch (c) { // 根据枚举类型对象做不同操作
   case Enum_A:
    System.out.println("doit2() Enum_A");
    break;
   case Enum_B:
    System.out.println("doit2() Enum_B");
    break;
  }
 }
 
 public static void main(String[] args) {
  Sample.doit(Constants.Enum_A); // 使用接口中定义的常量
  Sample.doit2(Constants2.Enum_A); // 使用枚举类型中的常量
  Sample.doit2(Constants2.Enum_B); // 使用枚举类型中的常量
  Sample.doit(3);
  // Sample.doit2(3);
 }
}

原创粉丝点击