Path: csiph.com!v102.xanadu-bbs.net!xanadu-bbs.net!feeder.erje.net!1.eu.feeder.erje.net!newsfeed.fsmpi.rwth-aachen.de!newsfeed.straub-nv.de!news-1.dfn.de!news.dfn.de!cache.uni-koblenz.de!not-for-mail From: Tassilo Horn Newsgroups: comp.lang.java.programmer Subject: Re: enum, what is it good for? Date: Tue, 21 Apr 2015 05:37:17 +0200 Organization: University Koblenz-Landau Campus Koblenz Lines: 49 Message-ID: <87a8y2w3rm.fsf@gnu.org> References: NNTP-Posting-Host: 2.161.236.134 Mime-Version: 1.0 Content-Type: text/plain; charset=utf-8 Content-Transfer-Encoding: 8bit X-Trace: cache.uni-koblenz.de 1429587438 19985 2.161.236.134 (21 Apr 2015 03:37:18 GMT) X-Complaints-To: news@cache.uni-koblenz.de NNTP-Posting-Date: Tue, 21 Apr 2015 03:37:18 +0000 (UTC) User-Agent: Gnus/5.130012 (Ma Gnus v0.12) Emacs/25.0.50 (gnu/linux) Cancel-Lock: sha1:e/FjO3AiyMJee5NkXLHsiJxHb58= Xref: csiph.com comp.lang.java.programmer:31590 ram@zedat.fu-berlin.de (Stefan Ram) writes: > I never use »enum«, so I thought that maybe I should give it > a try. I wrote: > > enum Square > { O( -1 ), Z( 0 ), X( 1 ); > private final int state; > Square( final int state ){ this.state = state; } > public int value() { return state; }} > > But I was not feeling well with this (because I though O > might have the field »state« /and/ also another »internal« > hidden value, which seems to be redundant) and rewrote it > into: Indeed, that's the case. But as long as you want a successive numbering, you can compute that with ordinal(). The ordinals of enum constants tell the order of their declaration starting with 0. enum Square { O, Z, X; public int getValue() { return ordinal() - 1; } } > class Square > { public static Square O = new Square( -1 ); > public static Square Z = new Square( 0 ); > public static Square X = new Square( 1 ); > private final int state; > private Square( final int state ){ this.state = state; } > public int value() { return state; }} > > I can use »Square.X« with both of these notations. > > So, is there any reason to prefer »enum« to »class«? You can use enum constants in a switch statement: switch (mySquare) { case O: ... case Z: ... case X: ... } You couldn't do that if Square was a class. Bye, Tassilo