Java Notes

Shadowing this

When an inner class refers to this, it refers to the current instance of the inner class. To refer to the instance of the outer class from the inner class, this must be qualified by the name of the outer class.

Example of referring to outer this from inner class

  1 
  2 
  3 
  4 
  5 
  6 
  7 
  8 
  9 
 10 
 11 
 12 
 13 
 14 
 15 
 16 
 17 
 18 
 19 
 20 
 21 
 22 
// ShadowThis.java -- Illustrate shadowing of this.
// Fred Swartz - 2003 - Jun

class ShadowThis {
    public static void main(String[] args) {
        ShadowThis st = new ShadowThis();
        st.testOuter();
    }//end main
    
    private void testOuter() {
        System.out.println(this);
        InnerShadowThis ist = new InnerShadowThis();
        ist.testInner();
    }//end test
    
    class InnerShadowThis {
        void testInner() {
            System.out.println(this);
            System.out.println(ShadowThis.this);
        }
    }//end class InnerShadowThis
}//end class ShadowThis
Produces the following output.
ShadowThis@601bb1
ShadowThis$InnerShadowThis@ea2dfe
ShadowThis@601bb1

Typical usage

The above example fails to show why referencing an outer this might be used. A common situation is to implement an action listener as an inner class of a JPanel. If the listener wants to display a dialog (eg, a JFileChooser), it may tell which component to center the dialog over. The component is exactly the outer this. For example, this is from an inner class listener that wants to center a file dialog over the current TestGUI panel.
int retval = fileChooser.showOpenDialog(TestGUI.this);
Some IDEs put no code in an inner class listener except a call to an outer method to process the action. The same code could be used, but the need to refer to the outer this is no longer necessary.