栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

如何启用枚举继承

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

如何启用枚举继承

您不能具有另一个

enum
扩展
enum
,也
enum
不能通过继承将值“添加”到现有值。

但是,

enum
可以实现
interface
。

我要做的是让原始

enum
实现标记
interface
(即没有方法声明),然后您的客户端可以创建自己的
enum
实现
interface
。

然后,您的

enum
价值观将被他们的共同点所引用
interface
。

为了加强要求,您可以让介面宣告相关的方法,例如在您的情况下,在的行中

public String getHTTPMethodType();
。

这将强制实现

enum
s提供该方法的实现。

此设置加上适当的API文档应有助于以相对受控的方式添加功能。

独立的示例 (不要介意这里的懒惰名称)

package test;import java.util.ArrayList;import java.util.List;public class Main {    public static void main(String[] args) {        List<HTTPMethodConvertible> blah = new ArrayList<>();        blah.add(LibraryEnum.FIRST);        blah.add(ClientEnum.BLABLABLA);        for (HTTPMethodConvertible element: blah) { System.out.println(element.getHTTPMethodType());        }    }    static interface HTTPMethodConvertible {        public String getHTTPMethodType();    }    static enum LibraryEnum implements HTTPMethodConvertible {        FIRST("first"),        SECOND("second"),        THIRD("third");        String httpMethodType;        LibraryEnum(String s) { httpMethodType = s;        }        public String getHTTPMethodType() { return httpMethodType;        }    }    static enum ClientEnum implements HTTPMethodConvertible {        FOO("GET"),BAR("PUT"),BLAH("OPTIONS"),MEH("DELETE"),BLABLABLA("POST");        String httpMethodType;        ClientEnum(String s){ httpMethodType = s;        }        public String getHTTPMethodType() { return httpMethodType;        }    }}

输出量

firstPOST


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/507356.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号