{"id":65,"date":"2020-12-31T22:03:17","date_gmt":"2020-12-31T22:03:17","guid":{"rendered":"https:\/\/bhiggs.x10hosting.com\/practical-java-programming\/?page_id=65"},"modified":"2021-01-09T22:19:20","modified_gmt":"2021-01-09T22:19:20","slug":"inner-classes","status":"publish","type":"page","link":"https:\/\/bhiggs.x10hosting.com\/PracticalJavaProgramming\/course-topics\/inner-classes\/","title":{"rendered":"Inner Classes"},"content":{"rendered":"<div id=\"ez-toc-container\" class=\"ez-toc-v2_0_83 counter-hierarchy ez-toc-counter ez-toc-grey ez-toc-container-direction\">\n<p class=\"ez-toc-title\" style=\"cursor:inherit\">Table of Contents<\/p>\n<label for=\"ez-toc-cssicon-toggle-item-6a06ee0bee7d3\" class=\"ez-toc-cssicon-toggle-label\"><span class=\"\"><span class=\"eztoc-hide\" style=\"display:none;\">Toggle<\/span><span class=\"ez-toc-icon-toggle-span\"><svg style=\"fill: #999;color:#999\" xmlns=\"http:\/\/www.w3.org\/2000\/svg\" class=\"list-377408\" width=\"20px\" height=\"20px\" viewBox=\"0 0 24 24\" fill=\"none\"><path d=\"M6 6H4v2h2V6zm14 0H8v2h12V6zM4 11h2v2H4v-2zm16 0H8v2h12v-2zM4 16h2v2H4v-2zm16 0H8v2h12v-2z\" fill=\"currentColor\"><\/path><\/svg><svg style=\"fill: #999;color:#999\" class=\"arrow-unsorted-368013\" xmlns=\"http:\/\/www.w3.org\/2000\/svg\" width=\"10px\" height=\"10px\" viewBox=\"0 0 24 24\" version=\"1.2\" baseProfile=\"tiny\"><path d=\"M18.2 9.3l-6.2-6.3-6.2 6.3c-.2.2-.3.4-.3.7s.1.5.3.7c.2.2.4.3.7.3h11c.3 0 .5-.1.7-.3.2-.2.3-.5.3-.7s-.1-.5-.3-.7zM5.8 14.7l6.2 6.3 6.2-6.3c.2-.2.3-.5.3-.7s-.1-.5-.3-.7c-.2-.2-.4-.3-.7-.3h-11c-.3 0-.5.1-.7.3-.2.2-.3.5-.3.7s.1.5.3.7z\"\/><\/svg><\/span><\/span><\/label><input type=\"checkbox\"  id=\"ez-toc-cssicon-toggle-item-6a06ee0bee7d3\"  aria-label=\"Toggle\" \/><nav><ul class='ez-toc-list ez-toc-list-level-1 ' ><li class='ez-toc-page-1 ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-1\" href=\"https:\/\/bhiggs.x10hosting.com\/PracticalJavaProgramming\/course-topics\/inner-classes\/#What_are_Inner_Classes\" >What are Inner Classes?<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-2\" href=\"https:\/\/bhiggs.x10hosting.com\/PracticalJavaProgramming\/course-topics\/inner-classes\/#A_Stack_Class\" >A Stack Class<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-3\" href=\"https:\/\/bhiggs.x10hosting.com\/PracticalJavaProgramming\/course-topics\/inner-classes\/#Enumerating_a_Stack\" >Enumerating a Stack<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-4\" href=\"https:\/\/bhiggs.x10hosting.com\/PracticalJavaProgramming\/course-topics\/inner-classes\/#Running_the_Program\" >Running the Program<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-5\" href=\"https:\/\/bhiggs.x10hosting.com\/PracticalJavaProgramming\/course-topics\/inner-classes\/#Inner_Class_Types\" >Inner Class Types<\/a><ul class='ez-toc-list-level-4' ><li class='ez-toc-heading-level-4'><a class=\"ez-toc-link ez-toc-heading-6\" href=\"https:\/\/bhiggs.x10hosting.com\/PracticalJavaProgramming\/course-topics\/inner-classes\/#Static_Member_Classes\" >Static Member Classes<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-4'><a class=\"ez-toc-link ez-toc-heading-7\" href=\"https:\/\/bhiggs.x10hosting.com\/PracticalJavaProgramming\/course-topics\/inner-classes\/#Example_1\" >Example 1<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-4'><a class=\"ez-toc-link ez-toc-heading-8\" href=\"https:\/\/bhiggs.x10hosting.com\/PracticalJavaProgramming\/course-topics\/inner-classes\/#An_Improvement\" >An Improvement<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-4'><a class=\"ez-toc-link ez-toc-heading-9\" href=\"https:\/\/bhiggs.x10hosting.com\/PracticalJavaProgramming\/course-topics\/inner-classes\/#Example_2\" >Example 2<\/a><\/li><\/ul><\/li><\/ul><\/nav><\/div>\n\n<h3 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"What_are_Inner_Classes\"><\/span>What are Inner Classes?<span class=\"ez-toc-section-end\"><\/span><\/h3>\n\n\n\n<p>An <em>inner class<\/em> is one that is defined within another class.<\/p>\n\n\n\n<p>Why is this good thing?&nbsp; Here are some reasons:<\/p>\n\n\n\n<ul class=\"wp-block-list\"><li>An inner class can make clear an explicit relationship with the enclosing class.<\/li><li>An inner class can be hidden within the enclosing class. (Data hiding\/encapsulation.)<\/li><li>Certain kinds of inner classes can access all the fields and methods within the enclosing class, which can be very helpful.<\/li><\/ul>\n\n\n\n<p>The bottom line is that using inner classes can lead to more readable, more maintainable, and more reliable code.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Nested Classes in C++<\/h2>\n\n\n\n<p>C++ does not have inner classes, per se.&nbsp; It has only&nbsp;<em>nested classes<\/em>.&nbsp;<\/p>\n\n\n\n<p>What&#8217;s the difference?&nbsp; C++ <em>nested classes<\/em> is a relationship between classes, as opposed to between objects.&nbsp; As we&#8217;ll see, Java inner classes usually do have a relationship between objects.<\/p>\n\n\n\n<p>Here&#8217;s an example of C++ nested classes. (Note that the implementation isn&#8217;t completely spelled out, because we don&#8217;t want to get bogged down in details that are not relevant to the topic at hand.)<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: cpp; auto-links: false; highlight: [27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96]; title: ; quick-code: false; notranslate\" title=\"\">\n#ifndef __LIST_H\n#define __LIST_H\n\/\/\n\/\/ LinkedList.h\n\/\/\n\n#include &lt;string&gt;\nusing namespace std;\n\n\/\/\/\/\/\/\/\/\/\/\/ Class LinkedList \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nclass LinkedList\n{\n    class Link;     \/\/ Forward reference\npublic:\n    LinkedList();   \/\/ Constructor\n    ~LinkedList();  \/\/ Destructor\n    \/\/ Access\n    Link *GetFirst() const; \/\/ Returns ptr to first item in list\n    Link *GetLast() const;  \/\/ Returns ptr to last item in list\n    int GetCount() const;   \/\/ Returns count of items in list\n\n    \/\/ Operations\n    void Append(Link &amp;item); \/\/ Appends an item to the end of the list\n    void Purge();            \/\/ Removes all items from the list\n\n    \/\/\/\/\/\/\/\/\/\/ A public nested Iterator class \/\/\/\/\/\/\/\/\n    class Iterator\n    {\n    public:\n        Iterator(const LinkedList &amp;list);   \/\/ Constructor\n        ~Iterator();                        \/\/ Destructor\n\n        \/\/ Access\n        const LinkedList *GetList() const; \/\/ Return ptr to the iterator&#039;s list\n        Link *GetCurrent() const;    \/\/ Return ptr to current list item\n        Link *GetNext();             \/\/ Move to next item and return ptr to it\n        Link *GetPrevious();         \/\/ Move to previous item and return ptr to it\n        bool  AtFirst() const;       \/\/ return true if current item is first item\n        bool  AtLast() const;        \/\/ return true if current item is last item\n\n    private:\n        \/\/ Disable copy constructor for Iterator\n        Iterator(const Iterator &amp;);\n        \/\/ Disable assignment for Iterator\n        Iterator &amp;operator=(const Iterator &amp;);\n\n        \/\/ Data\n        const LinkedList *m_list;    \/\/ The list we are iterating through\n        Link   *m_current;           \/\/ Points to the current item in the list\n    };\n\nprivate:\n    \/\/ Disable copy constructor for LinkedList\n    LinkedList(const LinkedList &amp;);\n    \/\/ Disable assignment for LinkedList\n    LinkedList &amp;operator=(const LinkedList &amp;);\n\n    \/\/ Data members\n    Link *m_first;    \/\/ Pointer to the first list item\n    Link *m_last;    \/\/ Pointer to the last list item\n    int m_count;         \/\/ Count of list items currently in list\n\n    \/\/\/\/\/\/\/\/\/\/ A private nested Link class \/\/\/\/\/\/\/\/\/\/\/\/\/\/\n    class Link\n    {\n    public:\n        Link(void *data);    \/\/ Constructor (associates with data)\n        ~Link();            \/\/ Destructor\n\n        \/\/ Operations\n        void Add(LinkedList &amp;list, Link *prevItem);\n        \/\/ Add this Link to the specified list\n        \/\/ following the specified prevItem\n        \/\/ (if prevItem is NULL, place at front of list)\n\n        void Remove();            \/\/ Remove this list item from the list it is in\n\n        \/\/ Access member functions\n        Link *GetNext() const;     \/\/ Return ptr to next item in list\n        Link *GetPrevious() const; \/\/ Return ptr to previous item in list\n        const LinkedList *GetList() const;   \/\/ Return ptr to the list item&#039;s list\n        void *GetData();               \/\/ Returns ptr to data for item\n\n    private:\n        \/\/ Disable copy constructor for Link\n        Link(const Link &amp;);\n        \/\/ Disable assignment for Link\n        Link &amp;operator=(const Link &amp;);\n\n        \/\/ Data members\n        Link       *m_next;    \/\/ Pointer to next item in the list\n        Link       *m_prev;    \/\/ Pointer to previous item in the list\n        LinkedList *m_list;    \/\/ Pointer to the list the item currently is in\n        void       *m_data;    \/\/ Pointer to data\n    };\n};\n#endif \/\/ __LIST_H\n<\/pre><\/div>\n\n\n<p>The basic benefits of nested classes in C++ are:<\/p>\n\n\n\n<ul class=\"wp-block-list\"><li><strong>Access control<\/strong>&nbsp;&#8212; you can place a nested class in a private, public, or protected section of the enclosing class<\/li><li><strong>Naming<\/strong> &#8212; if the nested class is to be used from outside of the enclosing class, its name must be qualified by the enclosing class&#8217;s name.&nbsp; So, for example, if you wanted to use the above nested&nbsp;<code><strong>Iterator<\/strong><\/code>&nbsp;class from outside the&nbsp;<code><strong>LinkedList<\/strong><\/code>&nbsp;class, you would have to refer to it as follows: <strong>LinkedList::Iterator<\/strong><br>That is, you would have to explicitly qualify it with the enclosing class&#8217;s name.<\/li><\/ul>\n\n\n\n<h3 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"A_Stack_Class\"><\/span>A Stack Class<span class=\"ez-toc-section-end\"><\/span><\/h3>\n\n\n\n<p>Before we talk about inner or nested classes, let&#8217;s show an example of how we might implement something without those features.<\/p>\n\n\n\n<p>Here&#8217;s a very simple <strong>Stack<\/strong> class in Java:<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: java; auto-links: false; title: ; quick-code: false; notranslate\" title=\"\">\npackage examples;\n\n\/**\n * Stack implements a simple stack of integers\n *\/\npublic class Stack\n{\n  \/**\n   * Creates a stack of specified number of elements\n   *\/\n  public Stack(int size)\n  {\n    m_stackData = new int&#x5B;size];\n  }\n  \/**\n   * Pushes an integer value on the stack, \n   * or throws an exception, if insufficient space\n   *\/\n  public void push(int value) throws IllegalStateException\n  {\n    if (m_next &gt;= m_stackData.length)\n      throw new IllegalStateException(&quot;Stack full&quot;);\n    m_stackData&#x5B;m_next++] = value;\n  }\n  \/**\n   * Returns whether the stack is currently empty\n   *\/\n  public boolean isEmpty()\n  {\n    return (m_next == 0);\n  }\n  \/**\n   * Pops the top int value off the stack,\n   * or throws an exception if the stack is empty\n   *\/\n  public int pop() throws IllegalStateException\n  {\n    if (isEmpty())\n      throw new IllegalStateException(&quot;Stack empty&quot;);\n    return m_stackData&#x5B;--m_next]; \/\/ top item on stack\n  }\n  \/**\n   * Returns the current size of the stack\n   *\/\n  public int getStackSize()\n  {\n    return m_next;\n  }\n  \/**\n   * Returns the maximum size of the stack\n   *\/\n  public int getMaxStackSize()\n  {\n    return m_stackData.length;\n  }\n  \/**\n   * Return the value of the specified item in the stack\n   * or throws an exception if the index specified is invalid.\n   *\/\n  public int get(int index) throws IllegalArgumentException\n  {\n    if (index &lt; 0 || index &gt;= getStackSize())\n      throw new IllegalArgumentException(&quot;index = &quot; + index);\n    return m_stackData&#x5B;index];\n  }\n\n  private int&#x5B;] m_stackData;\n  private int   m_next = 0; \/\/ Index of last item in stack\n}\n<\/pre><\/div>\n\n\n<h3 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Enumerating_a_Stack\"><\/span>Enumerating a Stack<span class=\"ez-toc-section-end\"><\/span><\/h3>\n\n\n\n<p>Now, let&#8217;s implement a class whose job it will be to enumerate all the values in an instance of <strong>Stack<\/strong>.&nbsp; We&#8217;ll call it <strong>StackEnumerator<\/strong>, and as you might expect, it implements the <strong>Enumeration<\/strong> interface (I chose <strong>Enumeration<\/strong> rather than <strong>Iterator<\/strong> because it&#8217;s simpler):<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: java; auto-links: false; title: ; quick-code: false; notranslate\" title=\"\">\npackage examples;\n\nimport java.util.Enumeration;\n\n\/**\n * Class to iterate through an instance of the above Stack class\n *\/\nclass StackEnumerator implements Enumeration\n{\n  \/**\n   * Constructor associates the StackIterator with a Stack instance\n   *\/\n  public StackEnumerator(Stack theStack)\n  {\n    m_theStack = theStack;\n  }\n  \/**\n   * Returns whether there are more elements\n   *\/\n  public boolean hasMoreElements()\n  {\n    return m_current &lt; m_theStack.getStackSize() - 1;\n  }\n  \/**\n   * Returns the next element\n   *\/\n  public Object nextElement()\n  {\n    return m_theStack.get(++m_current);\n  }\n\n  private Stack m_theStack;\n  private int   m_current = -1; \/\/ Position &quot;before&quot; first stack element\n}\n<\/pre><\/div>\n\n\n<p>Note that, in order to implement this class, the <strong>Stack<\/strong> class needed to give it access to its internal structures &#8212; it calls the <strong>get()<\/strong> method of the <strong>Stack<\/strong> class.&nbsp; However, a <strong>get()<\/strong> method is not really a natural feature of a stack.&nbsp; In other words, we added an artifact to the Stack&#8217;s public interface (API), merely to accommodate the <strong>StackEnumerator<\/strong> class.&nbsp;&nbsp;<\/p>\n\n\n\n<p>This is not good practice!&nbsp; But, as you&#8217;ll see, we can use nested and inner classes to improve the situation.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Running_the_Program\"><\/span>Running the Program<span class=\"ez-toc-section-end\"><\/span><\/h3>\n\n\n\n<p>Now let&#8217;s see what our <strong>Stack<\/strong> and <strong>StackEnumerator<\/strong> classes can do. (Note that this is by no means a thorough test!)<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: java; auto-links: false; title: ; quick-code: false; notranslate\" title=\"\">\npackage examples;\n\n\/**\n * Tests the Stack and StackIterator classes\n *\/\npublic class StackTest\n{\n  \/**\n   * Main entry point\n   *\/\n  public static void main(String&#x5B;] args)\n  {\n    Stack aStack = new Stack(10);\n    for (int i = 0; i &lt; aStack.getMaxStackSize(); i++)\n      aStack.push(i*i);\n    \n    StackEnumerator enumerator = new StackEnumerator(aStack);\n    while (enumerator.hasMoreElements())\n    {\n      int value = (Integer) enumerator.nextElement();\n      System.out.print(&quot; &quot; + value);\n    }\n    System.out.println();\n  }\n}\n<\/pre><\/div>\n\n\n<p>As you can see, the main method creates an instance of <strong>Stack<\/strong>, pushes some values onto the stack, and then uses a <strong>StackEnumerator<\/strong> to enumerate all the values on the stack.&nbsp;<\/p>\n\n\n\n<p>When run, this program outputs the following:<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\"><strong> 0 1 4 9 16 25 36 49 64 81<\/strong><\/pre>\n\n\n\n<p>But continue on to find out how inner classes can improve the situation&#8230;<\/p>\n\n\n\n<h3 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Inner_Class_Types\"><\/span>Inner Class Types<span class=\"ez-toc-section-end\"><\/span><\/h3>\n\n\n\n<p>There are four types of inner classes:<\/p>\n\n\n\n<ul class=\"wp-block-list\"><li>Static Nested Member Classes and Interfaces<\/li><li>Member Classes<\/li><li>Local Classes<\/li><li>Anonymous Classes<\/li><\/ul>\n\n\n\n<p>For an inner lass example, see:<\/p>\n\n\n\n<p><a rel=\"noreferrer noopener\" href=\"https:\/\/docs.oracle.com\/javase\/tutorial\/java\/javaOO\/innerclasses.html\" target=\"_blank\">https:\/\/docs.oracle.com\/javase\/tutorial\/java\/javaOO\/innerclasses.html<\/a><\/p>\n\n\n\n<h4 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Static_Member_Classes\"><\/span>Static Member Classes<span class=\"ez-toc-section-end\"><\/span><\/h4>\n\n\n\n<p>First, we have&nbsp;<strong>static member classes (and static member interfaces).<\/strong> Such a class (or interface) is a&nbsp;<strong>static&nbsp;<\/strong>member of an enclosing top-level class or interface.&nbsp;<\/p>\n\n\n\n<blockquote class=\"wp-block-quote is-layout-flow wp-block-quote-is-layout-flow\"><p>Note that nested interfaces are&nbsp;<em>always implicitly static members of their enclosing class<\/em>.<\/p><\/blockquote>\n\n\n\n<p>A static member class behaves much like an ordinary top-level class, except:<\/p>\n\n\n\n<ul class=\"wp-block-list\"><li>It is enclosed within the namespace of the enclosing class, so references to it must be qualified<\/li><li>It can access the static members of the enclosing class<\/li><\/ul>\n\n\n\n<p>Let&#8217;s look at some examples&#8230;<\/p>\n\n\n\n<h4 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Example_1\"><\/span>Example 1<span class=\"ez-toc-section-end\"><\/span><\/h4>\n\n\n\n<p>Now, I&#8217;ve pulled the <strong>StackEnumerator<\/strong> class into the <strong>Stack<\/strong> class as a <em>static nested class.<\/em><\/p>\n\n\n\n<p>I made no changes to the contents of the <strong>StackEnumerator<\/strong> class in the process, although I changed its name to simply <strong>Enumerator<\/strong> &#8212; since it&#8217;s inside the <strong>Stack<\/strong> class, it should be clear that it&#8217;s a stack <strong>Enumerator<\/strong>.<\/p>\n\n\n\n<p>Here&#8217;s what the new <strong>Stack<\/strong> class looks like:<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: java; auto-links: false; highlight: [72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100]; title: ; quick-code: false; notranslate\" title=\"\">\npackage staticNesting;\n\nimport java.util.Enumeration;\n\n\/**\n * Stack implements a simple stack of integers\n *\/\npublic class Stack\n{\n  \/**\n   * Creates a stack of specified number of elements\n   *\/\n  public Stack(int size)\n  {\n    m_stackData = new int&#x5B;size];\n  }\n  \/**\n   * Pushes an integer value on the stack,\n   * or throws an exception, if insufficient space\n   *\/\n  public void push(int value) throws IllegalStateException\n  {\n    if (m_next &gt;= m_stackData.length)\n      throw new IllegalStateException(&quot;Stack full&quot;);\n    m_stackData&#x5B;m_next++] = value;\n  }\n  \/**\n   * Returns whether the stack is currently empty\n   *\/\n  public boolean isEmpty()\n  {\n    return (m_next == 0);\n  }\n  \/**\n   * Pops the top int value off the stack,\n   * or throws an exception if the stack is empty\n   *\/\n  public int pop() throws IllegalStateException\n  {\n    if (isEmpty())\n      throw new IllegalStateException(&quot;Stack empty&quot;);\n    return m_stackData&#x5B;--m_next]; \/\/ top item on stack\n  }\n  \/**\n   * Returns the current size of the stack\n   *\/\n  public int getStackSize()\n  {\n    return m_next;\n  }\n  \/**\n   * Returns the maximum size of the stack\n   *\/\n  public int getMaxStackSize()\n  {\n    return m_stackData.length;\n  }\n  \/**\n   * Return the value of the specified item in the stack\n   * or throws an exception if the index specified is invalid.\n   *\/\n  public int get(int index) throws IllegalArgumentException\n  {\n    if (index &lt; 0 || index &gt;= getStackSize())\n      throw new IllegalArgumentException(&quot;index = &quot; + index);\n    return m_stackData&#x5B;index];\n  }\n\n  private int&#x5B;] m_stackData;\n  private int   m_next = 0; \/\/ Index of last item in stack\n\n  \/**\n   * A static nested class to iterate through an instance of this Stack\n   *\/\n  public static class Enumerator implements Enumeration\n  {\n    \/**\n     * Constructor associates the StackIterator with a Stack instance\n     *\/\n    public Enumerator(Stack theStack)\n    {\n      m_theStack = theStack;\n    }\n    \/**\n     * Returns whether there are more elements\n     *\/\n    public boolean hasMoreElements()\n    {\n      return m_current &lt; m_theStack.getStackSize() - 1;\n    }\n    \/**\n     * Returns the next element\n     *\/\n    public Object nextElement()\n    {\n      return m_theStack.get(++m_current);\n    }\n    private Stack m_theStack;\n    private int   m_current = -1; \/\/ Position &quot;before&quot; first stack element\n  }\n}\n<\/pre><\/div>\n\n\n<p>Here&#8217;s how we can use the modified <strong>Stack<\/strong> and nested <strong>Enumerator<\/strong> classes:<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: java; auto-links: false; highlight: [17]; title: ; quick-code: false; notranslate\" title=\"\">\npackage staticNesting;\n\n\/**\n * Tests the Stack and StackIterator classes\n *\/\npublic class StackTest\n{\n  \/**\n   * Main entry point\n   *\/\n  public static void main(String&#x5B;] args)\n  {\n    Stack aStack = new Stack(10);\n    for (int i = 0; i &lt; aStack.getMaxStackSize(); i++)\n      aStack.push(i*i);\n\n    Stack.Enumerator enumerator = new Stack.Enumerator(aStack);\n    while (enumerator.hasMoreElements())\n    {\n      int value = (Integer) enumerator.nextElement();\n      System.out.print(&quot; &quot; + value);\n    }\n    System.out.println();\n  }\n}\n<\/pre><\/div>\n\n\n<p>All I had to do was change the two <strong>StackEnumerator<\/strong> references to <strong>Stack.Enumerator<\/strong>.&nbsp;<\/p>\n\n\n\n<p>When run, this program outputs the same values as before:<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\"><strong> 0 1 4 9 16 25 36 49 64 81<\/strong><\/pre>\n\n\n\n<p>But, we can improve things even more&#8230;<\/p>\n\n\n\n<h4 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"An_Improvement\"><\/span>An Improvement<span class=\"ez-toc-section-end\"><\/span><\/h4>\n\n\n\n<p>But we can do better than that!<\/p>\n\n\n\n<p>There are some deficiencies with this particular implementation:<\/p>\n\n\n\n<ul class=\"wp-block-list\"><li><strong>Stack.Enumerator<\/strong> still knows more about the internals of <strong>Stack<\/strong> than it should<\/li><li>Users need to know about the nested class in order to use it;&nbsp; this is really unnecessary detail for them to have to know.<\/li><\/ul>\n\n\n\n<p>So, let&#8217;s improve the situation&#8230;<\/p>\n\n\n\n<h4 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Example_2\"><\/span>Example 2<span class=\"ez-toc-section-end\"><\/span><\/h4>\n\n\n\n<p>To achieve these improvements, I&#8217;ve done the following:<\/p>\n\n\n\n<ul class=\"wp-block-list\"><li>Changed the nested <strong>Enumeration<\/strong> class to be a&nbsp;<code><strong>private<\/strong><\/code>&nbsp;static member of <strong>Stack<\/strong>.<\/li><li>Changed the <strong>Stack<\/strong>&#8216;s <strong>get()<\/strong> method to be private.<\/li><li>Added a new method to the Stack class:<br><strong>public Enumeration getEnumerator()<\/strong><br>By doing this, I can hide the existence of the <strong>Enumerator<\/strong> class.&nbsp; All the user needs to know is that there is an enumerator, and that it implements the <strong>Enumeration<\/strong> interface.<\/li><\/ul>\n\n\n\n<p>Here&#8217;s what the new <strong>Stack<\/strong> class looks like:<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: java; auto-links: false; highlight: [62,69,70,71,72,73,74,75,76,77,78,86]; title: ; quick-code: false; notranslate\" title=\"\">\npackage betterStaticNesting;\n\nimport java.util.Enumeration;\n\n\/**\n * Stack implements a simple stack of integers\n *\/\npublic class Stack\n{\n  \/**\n   * Creates a stack of specified number of elements\n   *\/\n  public Stack(int size)\n  {\n    m_stackData = new int&#x5B;size];\n  }\n  \/**\n   * Pushes an integer value on the stack,\n   * or throws an exception, if insufficient space\n   *\/\n  public void push(int value) throws IllegalStateException\n  {\n    if (m_next &gt;= m_stackData.length)\n      throw new IllegalStateException(&quot;Stack full&quot;);\n    m_stackData&#x5B;m_next++] = value;\n  }\n  \/**\n   * Returns whether the stack is currently empty\n   *\/\n  public boolean isEmpty()\n  {\n    return (m_next == 0);\n  }\n  \/**\n   * Pops the top int value off the stack,\n   * or throws an exception if the stack is empty\n   *\/\n  public int pop() throws IllegalStateException\n  {\n    if (isEmpty())\n      throw new IllegalStateException(&quot;Stack empty&quot;);\n    return m_stackData&#x5B;--m_next]; \/\/ top item on stack\n  }\n  \/**\n   * Returns the current size of the stack\n   *\/\n  public int getStackSize()\n  {\n    return m_next;\n  }\n  \/**\n   * Returns the maximum size of the stack\n   *\/\n  public int getMaxStackSize()\n  {\n    return m_stackData.length;\n  }\n  \/**\n   * Return the value of the specified item in the stack\n   * or throws an exception if the index specified is invalid.\n   *\/\n  private int get(int index) throws IllegalArgumentException\n  {\n    if (index &lt; 0 || index &gt;= getStackSize())\n      throw new IllegalArgumentException(&quot;index = &quot; + index);\n    return m_stackData&#x5B;index];\n  }\n\n  \/**\n   * Returns an instance of the Enumerator class to the caller\n   * as an Enumeration.  This is known as an &quot;opaque&quot; class.\n   * All the caller needs to know is that the class being returned\n   * implements the Enumeration interface.\n   *\/\n  public Enumeration getEnumerator()\n  {\n    return new Enumerator(this);\n  }\n\n  private int&#x5B;] m_stackData;\n  private int   m_next = 0; \/\/ Index of last item in stack\n\n  \/**\n   * A static nested lass to enumerate an instance of this Stack\n   *\/\n  private static class Enumerator implements Enumeration\n  {\n    \/**\n     * Constructor associates the Enumerator with a Stack instance\n     *\/\n    public Enumerator(Stack theStack)\n    {\n      m_theStack = theStack;\n    }\n    \/**\n     * Returns whether there are more elements\n     *\/\n    public boolean hasMoreElements()\n    {\n      return m_current &lt; m_theStack.getStackSize() - 1;\n    }\n    \/**\n     * Returns the next element\n     *\/\n    public Object nextElement()\n    {\n      return m_theStack.get(++m_current);\n    }\n    private Stack m_theStack;\n    private int   m_current = -1; \/\/ Position &quot;before&quot; first stack element\n  }\n}\n<\/pre><\/div>\n\n\n<p>Here&#8217;s how we can use this new <strong>Stack<\/strong> class:<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: java; auto-links: false; highlight: [3]; title: ; quick-code: false; notranslate\" title=\"\">\npackage betterStaticNesting;\n\nimport java.util.Enumeration;\n\n\/**\n * Tests the Stack and StackIterator classes\n *\/\npublic class StackTest\n{\n  \/**\n   * Main entry point\n   *\/\n  public static void main(String&#x5B;] args)\n  {\n    Stack aStack = new Stack(10);\n    for (int i = 0; i &lt; aStack.getMaxStackSize(); i++)\n      aStack.push(i*i);\n    \n    Enumeration enumerator = aStack.getEnumerator();\n    while (enumerator.hasMoreElements())\n    {\n      int value = (Integer) enumerator.nextElement();\n      System.out.print(&quot; &quot; + value);\n    }\n    System.out.println();\n  }\n}\n<\/pre><\/div>\n\n\n<p>Now, the caller knows nothing about <strong>Stack.Enumerator<\/strong>;&nbsp; s\/he only needs to know about <strong>Enumerator<\/strong>.&nbsp;<\/p>\n\n\n\n<p>When run, this program outputs the same values as before:<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\"><strong> 0 1 4 9 16 25 36 49 64 81<\/strong><\/pre>\n\n\n\n<p><\/p>\n","protected":false},"excerpt":{"rendered":"<p>What are Inner Classes? An inner class is one that is defined within another class. Why is this good thing?&nbsp; Here are some reasons: An inner class can make clear an explicit relationship with the enclosing class.An inner class can be hidden within the enclosing class. (Data hiding\/encapsulation.)Certain kinds of inner classes can access all [&hellip;]<\/p>\n","protected":false},"author":2,"featured_media":0,"parent":34,"menu_order":0,"comment_status":"closed","ping_status":"closed","template":"","meta":{"_eb_attr":"","_uag_custom_page_level_css":"","ocean_post_layout":"left-sidebar","ocean_both_sidebars_style":"","ocean_both_sidebars_content_width":0,"ocean_both_sidebars_sidebars_width":0,"ocean_sidebar":"ocs-course-topics-sidebar","ocean_second_sidebar":"0","ocean_disable_margins":"enable","ocean_add_body_class":"","ocean_shortcode_before_top_bar":"","ocean_shortcode_after_top_bar":"","ocean_shortcode_before_header":"","ocean_shortcode_after_header":"","ocean_has_shortcode":"","ocean_shortcode_after_title":"","ocean_shortcode_before_footer_widgets":"","ocean_shortcode_after_footer_widgets":"","ocean_shortcode_before_footer_bottom":"","ocean_shortcode_after_footer_bottom":"","ocean_display_top_bar":"default","ocean_display_header":"default","ocean_header_style":"","ocean_center_header_left_menu":"0","ocean_custom_header_template":"0","ocean_custom_logo":0,"ocean_custom_retina_logo":0,"ocean_custom_logo_max_width":0,"ocean_custom_logo_tablet_max_width":0,"ocean_custom_logo_mobile_max_width":0,"ocean_custom_logo_max_height":0,"ocean_custom_logo_tablet_max_height":0,"ocean_custom_logo_mobile_max_height":0,"ocean_header_custom_menu":"0","ocean_menu_typo_font_family":"0","ocean_menu_typo_font_subset":"","ocean_menu_typo_font_size":0,"ocean_menu_typo_font_size_tablet":0,"ocean_menu_typo_font_size_mobile":0,"ocean_menu_typo_font_size_unit":"px","ocean_menu_typo_font_weight":"","ocean_menu_typo_font_weight_tablet":"","ocean_menu_typo_font_weight_mobile":"","ocean_menu_typo_transform":"","ocean_menu_typo_transform_tablet":"","ocean_menu_typo_transform_mobile":"","ocean_menu_typo_line_height":0,"ocean_menu_typo_line_height_tablet":0,"ocean_menu_typo_line_height_mobile":0,"ocean_menu_typo_line_height_unit":"","ocean_menu_typo_spacing":0,"ocean_menu_typo_spacing_tablet":0,"ocean_menu_typo_spacing_mobile":0,"ocean_menu_typo_spacing_unit":"","ocean_menu_link_color":"","ocean_menu_link_color_hover":"","ocean_menu_link_color_active":"","ocean_menu_link_background":"","ocean_menu_link_hover_background":"","ocean_menu_link_active_background":"","ocean_menu_social_links_bg":"","ocean_menu_social_hover_links_bg":"","ocean_menu_social_links_color":"","ocean_menu_social_hover_links_color":"","ocean_disable_title":"default","ocean_disable_heading":"default","ocean_post_title":"","ocean_post_subheading":"","ocean_post_title_style":"","ocean_post_title_background_color":"","ocean_post_title_background":0,"ocean_post_title_bg_image_position":"","ocean_post_title_bg_image_attachment":"","ocean_post_title_bg_image_repeat":"","ocean_post_title_bg_image_size":"","ocean_post_title_height":0,"ocean_post_title_bg_overlay":0.5,"ocean_post_title_bg_overlay_color":"","ocean_disable_breadcrumbs":"default","ocean_breadcrumbs_color":"","ocean_breadcrumbs_separator_color":"","ocean_breadcrumbs_links_color":"","ocean_breadcrumbs_links_hover_color":"","ocean_display_footer_widgets":"default","ocean_display_footer_bottom":"default","ocean_custom_footer_template":"0","footnotes":""},"class_list":["post-65","page","type-page","status-publish","hentry","entry"],"uagb_featured_image_src":{"full":false,"thumbnail":false,"medium":false,"medium_large":false,"large":false,"1536x1536":false,"2048x2048":false,"ocean-thumb-m":false,"ocean-thumb-ml":false,"ocean-thumb-l":false},"uagb_author_info":{"display_name":"Bryan Higgs","author_link":"https:\/\/bhiggs.x10hosting.com\/PracticalJavaProgramming\/author\/bryan\/"},"uagb_comment_info":0,"uagb_excerpt":"What are Inner Classes? An inner class is one that is defined within another class. Why is this good thing?&nbsp; Here are some reasons: An inner class can make clear an explicit relationship with the enclosing class. An inner class can be hidden within the enclosing class. (Data hiding\/encapsulation.) Certain kinds of inner classes can&hellip;","_links":{"self":[{"href":"https:\/\/bhiggs.x10hosting.com\/PracticalJavaProgramming\/wp-json\/wp\/v2\/pages\/65","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/bhiggs.x10hosting.com\/PracticalJavaProgramming\/wp-json\/wp\/v2\/pages"}],"about":[{"href":"https:\/\/bhiggs.x10hosting.com\/PracticalJavaProgramming\/wp-json\/wp\/v2\/types\/page"}],"author":[{"embeddable":true,"href":"https:\/\/bhiggs.x10hosting.com\/PracticalJavaProgramming\/wp-json\/wp\/v2\/users\/2"}],"replies":[{"embeddable":true,"href":"https:\/\/bhiggs.x10hosting.com\/PracticalJavaProgramming\/wp-json\/wp\/v2\/comments?post=65"}],"version-history":[{"count":14,"href":"https:\/\/bhiggs.x10hosting.com\/PracticalJavaProgramming\/wp-json\/wp\/v2\/pages\/65\/revisions"}],"predecessor-version":[{"id":617,"href":"https:\/\/bhiggs.x10hosting.com\/PracticalJavaProgramming\/wp-json\/wp\/v2\/pages\/65\/revisions\/617"}],"up":[{"embeddable":true,"href":"https:\/\/bhiggs.x10hosting.com\/PracticalJavaProgramming\/wp-json\/wp\/v2\/pages\/34"}],"wp:attachment":[{"href":"https:\/\/bhiggs.x10hosting.com\/PracticalJavaProgramming\/wp-json\/wp\/v2\/media?parent=65"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}