<?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/"
	>

<channel>
	<title>Smartkey - Java Software Consultancy &#187; Inner classes</title>
	<atom:link href="http://blog.smartkey.co.uk/tag/inner-classes/feed/" rel="self" type="application/rss+xml" />
	<link>http://blog.smartkey.co.uk</link>
	<description></description>
	<lastBuildDate>Tue, 13 Dec 2011 15:03:46 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.8.4</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>The Details of Member Level Inner Class Syntax</title>
		<link>http://blog.smartkey.co.uk/2009/11/details-of-inner-class-syntax/</link>
		<comments>http://blog.smartkey.co.uk/2009/11/details-of-inner-class-syntax/#comments</comments>
		<pubDate>Tue, 17 Nov 2009 15:52:46 +0000</pubDate>
		<dc:creator>Steve Neal</dc:creator>
				<category><![CDATA[Development]]></category>
		<category><![CDATA[Java Programming]]></category>
		<category><![CDATA[Inner classes]]></category>
		<category><![CDATA[Java]]></category>

		<guid isPermaLink="false">http://blog.smartkey.co.uk/?p=511</guid>
		<description><![CDATA[Inner classes offer are a powerful extension to Java's object model. However, the syntax for some of the more advanced features of member inner classes is quite tricky to get to grips with. In this article I'll explain the full details of this syntax.]]></description>
			<content:encoded><![CDATA[<p>Inner classes offer are a powerful extension to Java&#8217;s object model. However, the syntax for some of the more advanced features of member inner classes is quite tricky to get to grips with. In a <a href="/2009/11/programming-with-inner-classes-in-java/">previous article</a>, I discussed the different types of inner classes along with a demonstration of how they are most commonly used. In this article I&#8217;ll explain the full details of the inner class syntax in Java.</p>
<h3>The basics</h3>
<p>To define an inner class, just define one class within another:</p>
<pre class="brush: java">
public class Outer {
    public class Inner {

    }
}
</pre>
<p>Generally, the outer class will be responsible for creating instances of the inner classes and this could be done in the methods of the outer class, for example here where the outerClassesMethod creates an inner class instance and calls its method (lines 7-8) :</p>
<pre class="brush: java">
public class Outer {

    private String message = &quot;foo&quot;;

    public void outerClassesMethod() {
        //create an inner object to do the work
        Inner ii = new Inner();
        ii.innerClassesMethod();
    }

    private class Inner {
        private void innerClassesMethod() {
            System.out.println(message);
        }
    }
}
</pre>
<p>Note above that the inner classes method (line 12), although private, can still be called by the outer class. Also note that the private message field on the outer class (line 3) can be accessed from the inner class. A call to the outerClassesMethod will cause the innerClassesMethod to be called and the message &#8216;<strong>foo</strong>&#8216; to be printed to std out. </p>
<h3>What about &#8216;this&#8217; ?</h3>
<p>Each object in a Java application can refer to itself using the &#8216;this&#8217; reference. When an instance of an inner class is created, it is created within the instance that created it; so what effect does this have on &#8216;this&#8217; reference?</p>
<p>In fact, inner class instances have more than one &#8216;this&#8217; reference: one that refers to the instance of the inner instance, and one that refers to the outer instance. Consider this simple change to the example:</p>
<pre class="brush: java">
public class Outer {

    private String message = &quot;foo&quot;;

    public void outerClassesMethod() {
        //create an inner object to do the work
        Inner ii = new Inner();
        ii.innerClassesMethod();
    }

    private class Inner {
        private String message = &quot;bar&quot;;

        private void innerClassesMethod() {
            System.out.println(message);
        }
    }
}
</pre>
<p>Now that the inner class also has a field named message, the text &#8216;<strong>bar</strong>&#8216; will be printed out instead of &#8216;foo&#8217;.</p>
<p>The reason for this is that the inner classes message field has shadowed the outer classes one. The inner classes println call (line 15) would have the exact same behaviour if it were written as:</p>
<pre class="brush: java">
System.out.println(this.message);
</pre>
<p>if we want to access the message field on the outer class, then we need to use a &#8216;this&#8217; reference for the outer instance; we do this by pre-pending the class name to &#8216;this&#8217; as follows:</p>
<pre class="brush: java">
System.out.println(Outer.this.message);
</pre>
<p>substituting the println statement with the one shown above, will access the message field on the Outer class and cause &#8216;<strong>foo</strong>&#8216; to be printed out once again.</p>
<h3>Creating inner instances from outside the outer class</h3>
<p>As noted above, the inner instances will generally be created within the outer class. However, it is possible for inner instances to be created in other places too; for example, a factory class could be used to create the outer objects and also the inner objects that they will contain. </p>
<p>To demonstrate this scenario, we&#8217;ll use a slightly revised example where the inner class, and its method, have been made publicly visible. Note also that the outer class now has a constructor (lines 4-6) that will allow us to initialise its private message field (line 3) :</p>
<pre class="brush: java">
public class Outer {

    private String message;

    public Outer(String message) {
        this.message = message;
    }

    public class Inner {
        public void innerClassesMethod() {
            System.out.println(message);
        }
    }
}
</pre>
<p>If our factory class is to create the inner class instances, then it must associate them with an outer instance. In order to do this the new keyword must be scoped to a particular outer instance using this somewhat cumbersome syntax:</p>
<pre class="brush: java">
Outer o = new Outer(&quot;foo&quot;);
Outer.Inner i = o.new Inner();
i.innerClassesMethod();
</pre>
<p>Note the use of the new keyword (line 2) is prepended with the outer object reference (i.e. <strong>o.new</strong>). It is this outer reference that will be accessible within the inner object&#8217;s methods using the &#8216;this&#8217; syntax explained above.</p>
<p>So, when the call to the inner classes method is made (on line 3), the private message field of the outer instance will be printed out &#8211; i.e. we&#8217;ll see &#8216;<strong>foo</strong>&#8216; appear in std out.</p>
<h3>Static inner classes</h3>
<p>The static modifier can be applied to member level classes in much the same was as it can with the fields and methods of that class. As with fields and methods, use of the static modifier pretty much turns off OO. </p>
<pre class="brush: java">
public class Outer {

    private String message;

    static class Inner {
        private String message;

        public void innerClassesMethod() {
            //can access the message field defined on this class:
            System.out.println(this.message);

            //can&#039;t access the one from the outer class though:
            System.out.println(Outer.this.message);
        }
    }
}
</pre>
<p>In much the same way as a static method is not associated with an object instance, objects created from static inner class definitions are not associated with an outer object instance either.</p>
<p>Static inner classes therefore do not have a second this reference, and cannot access the non-static fields of the outer class (line 13 in the above example would produce a compiler error). Effectively, inner classes are just regular classes defined within an outer classes name-space. </p>
]]></content:encoded>
			<wfw:commentRss>http://blog.smartkey.co.uk/2009/11/details-of-inner-class-syntax/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Programming with Inner Classes in Java</title>
		<link>http://blog.smartkey.co.uk/2009/11/programming-with-inner-classes-in-java/</link>
		<comments>http://blog.smartkey.co.uk/2009/11/programming-with-inner-classes-in-java/#comments</comments>
		<pubDate>Sun, 08 Nov 2009 17:12:40 +0000</pubDate>
		<dc:creator>Steve Neal</dc:creator>
				<category><![CDATA[Development]]></category>
		<category><![CDATA[Java Programming]]></category>
		<category><![CDATA[Inner classes]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Swing]]></category>

		<guid isPermaLink="false">http://blog.smartkey.co.uk/?p=400</guid>
		<description><![CDATA[Inner classes are an advanced programming feature in Java. They add another dimension to the concept of Object Oriented programming by allowing objects to not only reside alongside one another, but also within one another too. In this post I'll explain how inner classes work with the help of an example that illustrates their most common use: Swing GUI programming.
]]></description>
			<content:encoded><![CDATA[<p>Inner classes are an advanced programming feature in Java. They add another dimension to the concept of Object Oriented programming by allowing objects to not only reside alongside one another, but also within one another too. In this post I&#8217;ll explain how inner classes work with the help of an example that illustrates their most common use: Swing GUI programming.</p>
<h3>Extending the Object Oriented Programming Model</h3>
<p>Encapsulation can be regarded as a barrier that an object puts up to protect itself from other objects. Within an object we generally expect there to be fields (that each object will have it&#8217;s own instance of) and methods (that can be called to affect that object). Inner classes extend Java&#8217;s OO model by also allowing objects to be created within an object, thus making the code within an object truly object oriented.</p>
<p>To demonstrate this, lets start by looking at some less-than-ideal Swing GUI code. The DemoUI class is a simple application frame that uses a WindowCloser object as a listener for its window events. The code for both of these classes is shown here:</p>
<pre class="brush: java">
public class DemoUI extends JFrame {
    public DemoUI() {
        //add the window closing event listener
        this.addWindowListener(new WindowCloser(this));
    }

    public void shutdown() {
        int answer = JOptionPane.showConfirmDialog(this, &quot;Are you sure?&quot;);
        if (answer == JOptionPane.YES_OPTION) {
            System.exit(0);
        }
    }
}

class WindowCloser extends WindowAdapter {
    private DemoUI demoUI;

    public WindowCloser(DemoUI demoUI) {
        this.demoUI = demoUI;
    }

    public void windowClosing(WindowEvent windowEvent) {
        demoUI.shutdown();
    }
}
</pre>
<p>When the user clicks application frame&#8217;s close button (i.e. the cross button on the frame&#8217;s title bar), the windowClosing method will be called on the event listener which will, in turn, call the shutdown method of the frame. The shutdown method prompts the user to make sure that they want to quit before calling System.exit(&#8230;) to exit the application.</p>
<p>Although a fairly simple example, this code is more complex than it need be. The reason for this complexity stems from the fact that the objects created from these classes are completely separate from one another, we could picture these objects as follows:</p>
<p><img class="aligncenter size-full wp-image-442" title="outer" src="http://blog.smartkey.co.uk/wp-content/uploads/2009/11/outer1.png" alt="outer" width="310" height="84" /></p>
<p>Because these objects would otherwise have no association with one another, we must provide a reference from the listener to the frame in order that the frame&#8217;s shutdown method may be called by the listener. It also means that the frame&#8217;s shutdown method cannot be declared private, thus weakening its encapsulation.</p>
<h3>Applying Inner Classes</h3>
<p>If we make the listener an inner class of the frame, then it will have access to all members of the frame (even private ones). We do this simply by moving the listener class definition inside the frame class:</p>
<pre class="brush: java">
public class DemoUI extends JFrame {
    public DemoUI() {
        //add the window closing event listener
        this.addWindowListener(new WindowCloser());
    }

    private void shutdown() {
        int answer = JOptionPane.showConfirmDialog(this, &quot;Are you sure?&quot;);
        if (answer == JOptionPane.YES_OPTION) {
            System.exit(0);
        }
    }

    private class WindowCloser extends WindowAdapter {
        public void windowClosing(WindowEvent windowEvent) {
            shutdown();
        }
    }
}
</pre>
<p>Now that the listener is declared as an inner class of the frame, instances of the listener will be created inside the enclosing frame instance. In contrast to the above example, this can now be pictured as follows:</p>
<p><img class="aligncenter size-full wp-image-433" title="inner" src="http://blog.smartkey.co.uk/wp-content/uploads/2009/11/inner1.png" alt="inner" width="232" height="84" /></p>
<p>Note that there is now no need to keep a reference to the frame instance from the listener as the listener object is implicitly associated with it. This means that the shutdown method, although declared as private on the frame, is still available to the listener. Finally, and for good measure, because the listener is only ever used by the frame, we can make its class definition private and prevent any other classes from accessing it.</p>
<h3>Method Level Inner Classes</h3>
<p>The example above shows an inner class being defined at the same level of scope as the methods and fields (aka the members) of the outer class. This type of inner class is therefore commonly referred to as a member level inner class.</p>
<p>In Java it is common to declare variables where they are first used. It is possible to do this with inner classes too. In this example the inner class has been declared just before it is used; i.e. within the constructor method of the frame:</p>
<pre class="brush: java">
public class DemoUI extends JFrame {
    public DemoUI() {
        //add the window closing event listener
        class WindowCloser extends WindowAdapter {
            public void windowClosing(WindowEvent windowEvent) {
                shutdown();
            }
        }
        this.addWindowListener(new WindowCloser());
    }

    private void shutdown() {
        int answer = JOptionPane.showConfirmDialog(this, &quot;Are you sure?&quot;);
        if (answer == JOptionPane.YES_OPTION) {
            System.exit(0);
        }
    }
}
</pre>
<p>A method level inner class can only be used in the method it is declared in and it is inherently private to that method. Classes defined at method level also have the additional advantage of being able to access local variables in that method, just so long as they are declared as final.</p>
<h3>Anonymous Inner Classes</h3>
<p>The next progression from a method level inner class is an anonymous inner class. In the previous example, the class was defined just before it was created and used. The name for the class was therefore only ever used in the definition and then in the subsequent call to create an instance of it. In cases such as this, it is possible to create and define the inner class in a single statement, rendering its name irrelevant:</p>
<pre class="brush: java">
public class DemoUI extends JFrame {
    public DemoUI() {
        //add the window closing event listener
        this.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent windowEvent) {
                shutdown();
            }
        });
    }

    private void shutdown() {
        int answer = JOptionPane.showConfirmDialog(this, &quot;Are you sure?&quot;);
        if (answer == JOptionPane.YES_OPTION) {
            System.exit(0);
        }
    }
}
</pre>
<p>You can see from this code that the inner class has now been created using the Java &#8216;new&#8217; operator but that the name WindowCloser is no longer used; just the supertype WindowAdapter is used instead and the implementation of the windowClosing method is simply specified in the curly braces following the normal constructor call.</p>
<p>This example demonstrates how to create an anonymous subclass of the WindowAdapter class which is an abstract class defined within the Swing APIs. You can create an anonymous subclass of any class though using this syntax; just place the code for the subclass within the curly braces and you&#8217;re done.</p>
<p>It is also possible to implement an interface using this syntax. So for example if there were a Quit button in our GUI, then we could implement the ActionListener interface for the event listener that reuses the shutdown method like so:</p>
<pre class="brush: java">
JButton quitButton = new JButton(&quot;Quit&quot;);
quitButton.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent actionEvent) {
        shutdown();
    }
});
</pre>
<h3>Summary</h3>
<p>The discussion I&#8217;ve presented above illustrates the most common use of inner classes but there are dozens of other uses; for example, the Spring data abstraction layer uses them to great effect, as does the Wicket web framework. </p>
<p>Fundamentally, inner classes in Java enable objects to be created within objects. This simple principle opens up a whole array of design choices for object aggregation. With careful consideration, inner classes allow your code to be more concise and maintainable than it might otherwise be. A good understanding of inner classes is therefore a key skill for any serious Java developer.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.smartkey.co.uk/2009/11/programming-with-inner-classes-in-java/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

