Top 10 in 2008
5 popular archives:
All selections are based on page views.
Best of 2008: A developer's list
JW blogger Dustin Marx names his top 10 technology events of 2008. Highlights include updates to Java SE 6, runtime support in OpenLaszlo 4.2, and the clash of the titans that occurred early in the year, when Sun acquired MySQL on the same day that Oracle announced its acquisition of BEA. No two lists are alike and it's not too late: What were your top 10 for 2008?
Also see:
How can we debug method calls that are not part of our own source code, say a call to JButton.setEnabled()? Java provides us with anonymous inner classes, which come in quite handy for this problem.
Usually, when we derive a class, we can override existing methods by providing a new one:
public class MyButton extends JButton {
public void setVisible( boolean visible ) {
// Rolling our own visibility
}
}
After instantiating buttons of type MyButton, any call to setVisible() will be handled by the code above. The problem is we do not want to declare a whole new class just to override one method,
especially when the number of instantiations is limited. Anonymous inner classes let us override methods on the fly at the
time of instantiation.
If we just want to roll our own visibility logic in one specific JButton, we just write the method as we declare the button:
JButton myButton = new JButton() {
public void setVisible( boolean visible ) {
// Rolling our own visibility
}
};
What happened here? The code between the curly braces declares the method setVisible() and overrides the one from JButton, but only for myButton. We have not altered the JButton class, we have not declared a new class, we have just given one special JButton its own visibility logic.
In object-oriented terminology, myButton is an object of an unnamed, hence anonymous, class derived from JButton.
When is overriding a method and creating an anonymous class on the fly useful? If you code with Swing, you have seen and coded
such a mechanism before when you added an event listener, say an ActionListener, to a GUI element. Now, imagine we have a big class with a bunch of buttons, where one button magically appears and disappears.
We want to know why this problem occurs. Use the code above and set a breakpoint in the body of the setVisible method. Then, as we run our program, the breakpoint will stop us just at the right place. With a look at the stack trace,
we find the culprit that called setVisible() unexpectedly and be able fix the problem.
Anonymous inner classes prove helpful for debugging those classes where the source code is unavailable. Even when source code
is available, setting a breakpoint in heavily used methods, such as setVisible(), might be cumbersome because we'll run into it for every instance of the class that implements setVisible(). Anonymous inner classes allow surgical debugging for one specific instance.
Archived Discussions (Read only)