import java.awt.*; import java.awt.event.*; class ButtonHolder { int m,n; Button b; ButtonHolder() { b = new Button( "hello" ); b.setSize(30,30); addOneListener(); addOneListener(); } void addOneListener() { b.addActionListener( new ActionListener() { int n=0; public void actionPerformed(ActionEvent e) { ++n; ++m; b.setLabel( "m = " + m + ", this.n = " + this.n ); //b.redraw(); } } ); } // Now, imagine you make three new ButtonHolder()s, // and each ButtonHolder makes two of these anonymous inner classes. // How many n's? How many m's? // Note that the instance of the ActionListeners are not fields // of ButtonHolder; their closure does include fields of ButtonHolder, though. // Also note that other parts of code (e.g. the awt event handler) // has references to the ActionListener, even though ButtonHolder() is not in its scope. public static void main(String[] args) throws InterruptedException { Frame f = new Frame(); ButtonHolder bh1 = new ButtonHolder(); ButtonHolder bh2 = new ButtonHolder(); f.setSize( 100, 100 ); f.add( bh1.b ); f.add( bh2.b ); f.setVisible(true); Thread.sleep(8000); System.out.println( "bh1.m = " + bh1.m + ", bh1.n = " + bh1.n + ", bh2.m = " + bh2.m + ", bh2.n = " + bh2.n ); } }