枚举类使用方法
下面例子包括内容:
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!
本文来自博客园,作者:月色深潭,交流群:733423266,转载请注明原文链接:https://www.cnblogs.com/moonpool/p/5877628.html