In Java Swing if you want to add a listener to a component, it would look something like this…
JButton j = new JButton();
int counter = 0;
j.addAncestorListener(new AncestorListener() {
@Override
public void ancestorMoved(AncestorEvent event) {
}
@Override
public void ancestorAdded(AncestorEvent event) {
counter++;
}
@Override
public void ancestorRemoved(AncestorEvent event) {
}
});
If I were able to create a new Java keyword and just say this….
JButton j = new JButton();
int counter = 0;
swinglistener (j, AncestorListener) {
ancestorAdded {
counter++;
}
}
…. to achieve the same effect. Would this code be more readable? Would it be better? What other aspects of “good” software design would this change achieve?
2
Assuming you have control over the interface, you’re basically describing Java 8’s default methods. You can define an implementation of interface methods that will be used if the implementing class does not explicitly override it.
public interface MyAncestorListener {
default void ancestorAdded(AncestorEvent event) {
}
default void ancestorMoved(AncestorEvent event) {
}
default void ancestorRemoved(AncestorEvent event) {
}
}
class MyAncestorListenerImpl implements MyAncestorListener {
@Override
public void ancestorMoved(AncestorEvent event) {
// Custom implementation here
}
}
If you don’t have the option of modifying the interface (such as in your Swing example), you can use an abstract base class to provide empty implementations for the interface methods.
public abstract class AbstractAncestorListener implements AncestorListener {
@Override
public void ancestorAdded(AncestorEvent event) {
}
@Override
public void ancestorMoved(AncestorEvent event) {
}
@Override
public void ancestorRemoved(AncestorEvent event) {
}
}
You can then override just the methods you need to implement.
JButton j = new JButton();
int counter = 0;
j.addAncestorListener(new AbstractAncestorListener() {
@Override
public void ancestorAdded(AncestorEvent event) {
counter++;
}
});