Java Reference
In-Depth Information
frame.setSize(250,200);
frame.setLayout(new FlowLayout());
frame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
Button red = new Button(“Red”);
red.addActionListener(new RedHandler());
frame.add(red);
frame.setVisible(true);
}
private class RedHandler implements ActionListener {
public void actionPerformed(ActionEvent e) {
frame.setBackground(Color.RED);
}
}
public static void main(String [] args) {
new SimpleWindow();
}
}
Notice both of the inner classes perform simple tasks that require the private frame fi eld,
making them good candidates for inner classes.
You should be aware, however, that inner classes go against some of the fundamental
OOP concepts, such as reuse of classes and high cohesion (discussed in Chapter 6).
Therefore, make sure inner classes make sense in your program's design and do not
unnecessarily add complexity to your top-level classes.
Static Nested Classes
A static nested class is a static class defi ned at the member level of an enclosing class. Static
nested classes are not inner classes. They do not have access to the fi elds and methods of the
enclosing class, and they can be instantiated without a corresponding instance of the outer class.
Search WWH ::




Custom Search