![]() |
![]() |
|
home—info—lectures—exams—archive
Java (with v1.5), anonymous inner classes have closures:
import java.awt.*;
import java.awt.event.*;
class ButtonHolder {
int m,n;
Button b;
ButtonHolder() {
b = new Button();
addOneListener();
addOneListener();
}
void addOneListener() {
b.addActionListener(
new ActionListener() {
int n=0;
public void actionPerformed(ActionEvent e) {
++n;
++m;
}
} );
}
// 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 <em>closure</em> 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.
} |
Dynamic scope: (Lisp; Perl.)
class Foo() {
int x = 3;
void foo() {
++x; // If dynamically scoped: refers to 'most recently declared' x
print(x); // in a *dynamic* sense!
}
void haha() {
foo();
}
void lala() {
int x = 9;
foo();
}
void gaga() {
int x = 5;
foo();
}
}
class Hoo() {
int x;
Foo.foo();
}
|
Other ways of controlling access:
home—info—lectures—exams—archive
| ©2008, Ian Barland, Radford University Last modified 2008.Oct.29 (Wed) |
Please mail any suggestions (incl. typos, broken links) to ibarland |
![]() |