<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	xmlns:georss="http://www.georss.org/georss" xmlns:geo="http://www.w3.org/2003/01/geo/wgs84_pos#" xmlns:media="http://search.yahoo.com/mrss/"
	>

<channel>
	<title>Umair&#039;s Blog &#187; puzzle</title>
	<atom:link href="http://umairsaeed.com/tag/puzzle/feed/" rel="self" type="application/rss+xml" />
	<link>http://umairsaeed.com</link>
	<description></description>
	<lastBuildDate>Fri, 20 Jan 2012 16:28:51 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.com/</generator>
<cloud domain='umairsaeed.com' port='80' path='/?rsscloud=notify' registerProcedure='' protocol='http-post' />
<image>
		<url>http://s2.wp.com/i/buttonw-com.png</url>
		<title>Umair&#039;s Blog &#187; puzzle</title>
		<link>http://umairsaeed.com</link>
	</image>
	<atom:link rel="search" type="application/opensearchdescription+xml" href="http://umairsaeed.com/osd.xml" title="Umair&#039;s Blog" />
	<atom:link rel='hub' href='http://umairsaeed.com/?pushpress=hub'/>
		<item>
		<title>Java Enum Puzzler</title>
		<link>http://umairsaeed.com/2009/09/29/java-enum-puzzler/</link>
		<comments>http://umairsaeed.com/2009/09/29/java-enum-puzzler/#comments</comments>
		<pubDate>Tue, 29 Sep 2009 22:31:33 +0000</pubDate>
		<dc:creator>Umair</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[enum]]></category>
		<category><![CDATA[puzzle]]></category>

		<guid isPermaLink="false">http://umairsd.wordpress.com/2009/09/29/java-enum-puzzler/</guid>
		<description><![CDATA[Recently, I ran into an interesting bit of code related to Java enumerations. Here’s a contrived minimal sample: When this code is run, an intuitive expectation is to see the following printed to the console: BRAVO CHARLIE ALPHA However, when &#8230; <a href="http://umairsaeed.com/2009/09/29/java-enum-puzzler/">Continue reading <span class="meta-nav">&#8594;</span></a><img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=umairsaeed.com&amp;blog=9333327&amp;post=27&amp;subd=umairsd&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>Recently, I ran into an interesting bit of code related to Java enumerations. Here’s a contrived minimal sample:</p>
<pre><pre class="brush: java;">
/*
 * Some arbitrary resource type
 */
interface Resource {
	public Resource getResource();
}

enum A implements Resource{
	ALPHA (B.BRAVO);
	
	private Resource res;
	private A (Resource res){ this.res = res; }
	public Resource getResource(){ return res; }
}

enum B implements Resource{
	BRAVO (C.CHARLIE);

	private Resource res;
	private B (Resource res){ this.res = res; }
	public Resource getResource(){ return res; }

}

enum C implements Resource{
	CHARLIE (A.ALPHA);

	private Resource res;
	private C (Resource res){ this.res = res; }
	public Resource getResource(){ return res; }
}


class EnumTester{
	public static void main(String [] args){
		System.out.println(A.ALPHA.getResource());	
		System.out.println(B.BRAVO.getResource());	
		System.out.println(C.CHARLIE.getResource());
	}
}
</pre></pre>
<p>When this code is run, an intuitive expectation is to see the following printed to the console:</p>
<blockquote>
<table border="0" cellspacing="0" cellpadding="2" width="37">
<tbody>
<tr>
<td valign="top" width="35"><font face="Courier New">BRAVO</font></td>
</tr>
<tr>
<td valign="top" width="35"><font face="Courier New">CHARLIE</font></td>
</tr>
<tr>
<td valign="top" width="35"><font face="Courier New">ALPHA</font></td>
</tr>
</tbody>
</table>
</blockquote>
<p>However, when I actually run the code we see:</p>
<blockquote>
<table border="0" cellspacing="0" cellpadding="2" width="37">
<tbody>
<tr>
<td valign="top" width="35"><font face="Courier New">BRAVO</font></td>
</tr>
<tr>
<td valign="top" width="35"><font face="Courier New">CHARLIE</font></td>
</tr>
<tr>
<td valign="top" width="35"><font face="Courier New">null</font></td>
</tr>
</tbody>
</table>
</blockquote>
<p>While this may seem a bit funky, the key is to understand what enum constants mean in Java. The key question to address is: “when is the constructor for an enumerated type invoked”. To answer this, it is helpful to remember that enum constants are implicitly <font face="Courier New"><font size="2">public static final</font>.</font> Java guarantees that:</p>
<ul>
<li>Static variables in a class are initialized before any object of that class can be created </li>
<li>Static variables in a class are initialized before any static method of the class runs </li>
</ul>
<p>Knowing this, the behavior of the above code snippet becomes clearer. Here’s what happens in the main method:</p>
<ol>
<li>The fun happens at line 35, when we print&#160;&#160; <font face="Courier New">A.<em>ALPHA</em>.getResource()</font>. Behind the scene, the class loader loads enumeration A into memory (i.e. initializes A). </li>
<li>Once A is loaded into memory, the enum constant <em><font face="Courier New">ALPHA</font></em> gets created via call to the constructor where <font face="Courier New">B.<em>BRAVO</em></font> is passed in as the argument. </li>
<li>At this point, enumeration B is initialized and enum constant <em><font face="Courier New">BRAVO</font></em> gets created via a call to the constructor where <font face="Courier New">C.<em>CHARLIE</em></font> is passed in as the argument. </li>
<li>Same as before, now enumeration C is initialized (i.e. loaded into memory). Now here’s where things become interesting. </li>
<li>Immediately after the initialization of C, we create the enum constant <em><font face="Courier New">CHARLIE</font></em> via a call to the constructor and pass in <font face="Courier New">A.<em>ALPHA</em></font> as the argument. However, <font face="Courier New">A.<em>ALPHA</em></font> has not been instantiated yet, and therefore enum constant <em><font face="Courier New">CHARLIE</font></em> gets null as the value of its resource instance variable.&#160; </li>
</ol>
<p>This means that once the statement <font face="Courier New">A.<em>ALPHA</em>.getResource()</font> is evaluated, A, B and C are all loaded into memory and all the corresponding enum constants have already been instantiated. Lines 35-37 simply then print the corresponding resources for each enum constant. </p>
</p>
<p><strong></strong></p>
</p>
<p><strong><font size="4">A Possible Solution</font></strong></p>
<p>It is obvious that the entire problem stems from the cyclic dependency between A, B and C. Usually (but <a href="http://beust.com/weblog/archives/000208.html" target="_blank">not always</a>), this is an indication of a bad design choice and the fix is to simply get rid of the cyclic dependency. Assuming we want to keep the dependency, what are our options then?</p>
<p>Our solutions lies in Java&#8217;s ability to allow <a href="http://java.sun.com/j2se/1.5.0/docs/guide/language/enums.html" target="_blank">instance-specific methods on enumerations</a>. This is shown in the code below.</p>
<p>Running the following code with the EnumTester main method above will give us the results we wanted, without the problems caused by the previous approach.</p>
<pre><pre class="brush: java;">
enum A implements Resource{
	ALPHA { public Resource getResource() {return B.BRAVO; } };
	
	public abstract Resource getResource();
}

enum B implements Resource{
	BRAVO { public Resource getResource() { return C.CHARLIE; } };
	
	public abstract Resource getResource();
}

enum C implements Resource{
	CHARLIE { public Resource getResource() { return A.ALPHA; }};
	
	public abstract Resource getResource();
}
</pre></pre>
<p>What do you think? Do you know of any other ways to resolve the cyclic dependency? Have you seen any other weirdness related to Java’s Enums? </p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/umairsd.wordpress.com/27/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/umairsd.wordpress.com/27/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/umairsd.wordpress.com/27/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/umairsd.wordpress.com/27/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/umairsd.wordpress.com/27/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/umairsd.wordpress.com/27/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/umairsd.wordpress.com/27/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/umairsd.wordpress.com/27/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/umairsd.wordpress.com/27/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/umairsd.wordpress.com/27/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/umairsd.wordpress.com/27/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/umairsd.wordpress.com/27/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/umairsd.wordpress.com/27/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/umairsd.wordpress.com/27/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=umairsaeed.com&amp;blog=9333327&amp;post=27&amp;subd=umairsd&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://umairsaeed.com/2009/09/29/java-enum-puzzler/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/3d8419a4ace3305d6791158454f7f874?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">umairsd</media:title>
		</media:content>
	</item>
	</channel>
</rss>
