public class SomeGUI extends JFrame { ... button member declarations ...
protected void buildGUI() { button1 = new JButton(); button2 = new JButton(); ...
button1.addActionListener( new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent e) { // do something } } ); …repeat for each button
如果应用一般内部类,程序就会像这样:
public class SomeGUI extends JFrame { ... button member declarations
// inner class definitions class Button1Handler implements ActionListener { public void actionPerformed(ActionEvent e) { // do something } } ... define an inner member class for each button
protected void buildGUI() { // initialize the buttons button1 = new JButton(); button2 = new JButton(); ...
// register an inner class action listener instance // for each button button1.addActionListener(new Button1Handler()); .. repeat for each button
没有东西是十全十美的,一样东西有它的长处必然会有它的短处。内部类也有它们不足的地方。从维护的角度来说,一个不熟练的开发人员就会觉得内部类难以理解。应用内部类会使增加你的类的代码总行数。此外,从开发的角度来说,大部分的Java工具都在对内部类的支持上都存在或多或少不足的地方。For example, I use IBM's VisualAge for Java for my day-to-day coding. While inner classes will compile within VisualAge, there is no inner class browser or template. Instead, you must simply type the inner class directly into the class definition. That unfortunately makes browsing the inner class difficult. It is also difficult to type since you lose many of VisualAge's code completion aids when you type into the class definition or use an inner class.
For example, I use IBM's VisualAge for Java for my day-to-day coding. While inner classes will compile within VisualAge, there is no inner class browser or template. Instead, you must simply type the inner class directly into the class definition. That unfortunately makes browsing the inner class difficult. It is also difficult to type since you lose many of VisualAge's code completion aids when you type into the class definition or use an inner class. 原文链接: