嵌套枚举 - 为什么使用它? [英] nested enum-why is it used?

查看:100
本文介绍了嵌套枚举 - 为什么使用它?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经看到在枚举中声明了一个枚举的构造。这是用于什么?

解决方案

Java中的枚举不能扩展,所以如果你想整理强烈相关的枚举一个地方可以使用这些嵌套的枚举结构。例如:

  public enum DepartmentsAndFaculties 
{
UN(null,UN,University ),
EF(UN,EF,Engineering Faculty),
CS(EF,CS,Computer Science& Engineering),
EE(EF, EE,电气工程);

private final DepartmentsAndFaculties parent;
private final String代码,标题;

DepartmentsAndFaculties(DepartmentsAndFaculties parent,String code,String title)
{
this.parent = parent;
this.code = code;
this.title = title;
}

public DepartmentsAndFaculties getParent()
{
return parent;
}

public String getCode()
{
return code;
}

public String getTitle()
{
return title;
}
}

这里,内部枚举由{parent enum,code ,标题}组合。示例用法:

  DepartmentsAndFaculties cs = DepartmentsAndFaculties.CS; 
cs.getTitle();

在构建分层实体/枚举时,您可以看到嵌套枚举的权力。


I have seen constructs with an enum declared inside an enum. What is this used for ?

解决方案

Enums in Java can't be extended, so if you wanna collate strongly-related enums in one place you can use these nested enum constructs. For example:

public enum DepartmentsAndFaculties
{
   UN (null, "UN", "University"),
   EF (UN,   "EF", "Engineering Faculty"),
   CS (EF,   "CS", "Computer Science & Engineering"),
   EE (EF,   "EE", "Electrical Engineering");

   private final DepartmentsAndFaculties parent;
   private final String code, title;

   DepartmentsAndFaculties(DepartmentsAndFaculties parent, String code, String title)
   {
       this.parent = parent;
       this.code   = code;
       this.title  = title;
   }

   public DepartmentsAndFaculties getParent()
   {
       return parent;
   }

   public String getCode()
   {
       return code;
   }

   public String getTitle()
   {
       return title;
   }
}

Here, inner enums consist of {parent enum, code, title} combinations. Example usage:

 DepartmentsAndFaculties cs = DepartmentsAndFaculties.CS;
 cs.getTitle();

You can see the power of nested enums when constructing hierarchical entities/enums.

这篇关于嵌套枚举 - 为什么使用它?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆