title: How does Java inheritance work when inner classes are involved
body: <p>I am having trouble understanding how inheritance works in Java when inner classes are present.  I'm currently working on something where a child class needs to slightly change the functionality of the inner class of it's parent.  I've come up with an simpler, analagous example below.</p>
  
  <p>I expected this code to print "I am a ChildClass.InnerClass" but instead it prints
  "I am a ParentClass.InnerClass".  Why is this?  Also, if I change the obj object in main
  to be of type ChildClass then the output changes to "I am a ChildClass.InnerClass".  Why is this?</p>
  
  <p>In general, what is the recommended way of altering the behavior of an object's parent class's inner object?</p>
  
  <pre><code>class InnerClassTest {
     //-----------------------------------------------------------------------
     // PARENT CLASS
     class ParentClass {
        public ParentClass() {
           x = new InnerClass();
        }
  
        InnerClass x;
  
        class InnerClass {
           public void speak() {
              System.out.println("I am a ParentClass.InnerClass");
           }
        }
     }
  
     //-----------------------------------------------------------------------
     // CHILD CLASS
     class ChildClass extends ParentClass {
        public ChildClass() {
           x = new InnerClass();
        }
  
        InnerClass x;
  
        class InnerClass extends ParentClass.InnerClass {
           public void speak() {
              System.out.println("I am a ChildClass.InnerClass");
           }
        }
     }
  
     //-----------------------------------------------------------------------
     // MAIN
     public static void main(String[] args) {
        ParentClass obj = (new InnerClassTest()).new ChildClass();
        obj.x.speak();
     }
  }
  </code></pre>