Path: csiph.com!v102.xanadu-bbs.net!xanadu-bbs.net!feeder.erje.net!eu.feeder.erje.net!eternal-september.org!feeder.eternal-september.org!news.eternal-september.org!.POSTED!not-for-mail From: markspace Newsgroups: comp.lang.java.programmer Subject: Re: use case for extending enum, but this is not possible in java Date: Sat, 14 Jun 2014 18:58:21 -0700 Organization: A noiseless patient Spider Lines: 68 Message-ID: References: Mime-Version: 1.0 Content-Type: text/plain; charset=ISO-8859-1; format=flowed Content-Transfer-Encoding: 7bit Injection-Date: Sun, 15 Jun 2014 01:58:29 +0000 (UTC) Injection-Info: mx05.eternal-september.org; posting-host="9358cda03e1e0dfd3c4b757daa608707"; logging-data="12003"; mail-complaints-to="abuse@eternal-september.org"; posting-account="U2FsdGVkX180WZa45dRvDErq/6/BvGMsus9BuhdMK2M=" User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:24.0) Gecko/20100101 Thunderbird/24.6.0 In-Reply-To: Cancel-Lock: sha1:L5jmdY686X5mnpYbXkbLa6fSdrY= Xref: csiph.com comp.lang.java.programmer:28741 On 6/14/2014 4:24 PM, Laura Schmidt wrote: > public void onListCommand (ListCommand cmd) > { > AppListCommand c = (AppListCommand) cmd; > > switch (c) > { > ... > } I have to agree with Marcel Muller here. Enums, the way you use them, are not polymorphic. And using a switch to emulate polymorphism is almost always a bad idea. See Replace Conditional with Polymorphism. http://www.refactoring.com/catalog/replaceConditionalWithPolymorphism.html However you can fake it a bit in Java. Java enum are sorta-kinda polymorphic. (I think that's the technical term.) interface MyCommand { Object eval(); } void onListCommand( MyCommand cmd ) { System.out.println( cmd.eval() ); } public enum ListCommand implements MyCommand { OPEN, EDIT, DELETE; public Object eval() { return this.ordinal(); } } public enum AppListCommand implements MyCommand { OPEN, CLOSE, SOMETHINGSPECIAL() { public Object eval() { return "Hi";}}; public Object eval() { return this.ordinal(); } } Not compiled or tested, although part was: public static void main( String[] args ) { onListCommand( AppListCommand.OPEN, AppListCommand.CLOSE, AppListCommand.SOMETHINGSPECIAL ); } private static void onListCommand( MyCommand... cmd ) { for( MyCommand x : cmd ) { System.out.println( x.eval() ); } } run: 0 1 Hi BUILD SUCCESSFUL (total time: 1 second)