zoukankan      html  css  js  c++  java
  • 枚举类使用方法

    下面例子包括内容:

    1.带有构造器的枚举类定义方法

    2.实现接口方法,以及以内部类的方式实现接口(采用内部类的方式实现接口可以使枚举值(枚举实例)的拥有不同方法以及不同的实现

    3.枚举的使用方法

    1 package com.myenum.test;
    2 
    3 public interface GenderDesc {
    4     String info();
    5 
    6 }
     1 package com.myenum.test;
     2 
     3 public enum Gender implements GenderDesc {
     4     MALE("男"), FEMALE("女"), BOY("男孩") {
     5         public String info() {
     6             return "this is a boy!";
     7         }
     8     };
     9 
    10     private final String name;
    11 
    12     private Gender(String string) {
    13         this.name = string;
    14     }
    15 
    16     public String getName() {
    17         return this.name;
    18     }
    19 
    20     @Override
    21     public String info() {
    22         return "this is a male or female";
    23 
    24     }
    25 
    26 }
     1 package com.myenum.test;
     2 
     3 public class CallTest {
     4 
     5     public static void main(String[] args) {
     6 
     7         System.out.println(Gender.MALE.getName());
     8         System.out.println(Gender.FEMALE.getName());
     9 
    10         for (Gender g : Gender.values()) {
    11             System.out.println(g.toString());
    12         }
    13 
    14         Gender m = Gender.valueOf("MALE");
    15         System.out.println(m.ordinal() 
    16                 + "  and  " + m.name() 
    17                 + "  and  " + m.getName() 
    18                 + "  and  " + m.info());
    19 
    20         Gender g = Enum.valueOf(Gender.class, "FEMALE");
    21         System.out.println(g.ordinal() 
    22                 + "  and  " + g.name() 
    23                 + "  and  " + g.getName() 
    24                 + "  and  " + g.info());
    25 
    26         Gender b = Enum.valueOf(Gender.class, "BOY");
    27         System.out.println(b.ordinal() 
    28                 + "  and  " + b.name() 
    29                 + "  and  " + b.getName() 
    30                 + "  and  " + b.info());
    31 
    32     }
    33 
    34 }

    执行结果:

    1 2 3 MALE
    4 FEMALE
    5 BOY
    6 0  and  MALE  and  男  and  this is a male or female
    7 1  and  FEMALE  and  女  and  this is a male or female
    8 2  and  BOY  and  男孩  and  this is a boy!
  • 相关阅读:
    [整理]解析Json需要设置Mime
    [整理]IE11中的WebGL探秘:渲染速度超Chrome
    [转载]详解主流浏览器多进程架构:Chrome、IE
    [转载]为什么浏览器会使用多进程架构
    [整理]win7下VS2010遇到内存不足解决方发
    [整理]WebAPI中应用oData
    [转载]NodeJS优缺点及适用场景讨论
    [转载]HTML5 真的会消灭原生App吗?
    [转载]微软VS2015支持Android和iOS编程
    VC++调试基础
  • 原文地址:https://www.cnblogs.com/moonpool/p/5877628.html
Copyright © 2011-2022 走看看