0

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?

  • 3
    Try googling "Java interface default methods". These were introduced in Java 8, and address at least your readability concern. – kiwiron Mar 30 '15 at 3:43
  • I didn't know about that use of the default keyword. Think it makes my swinglistener keyword redundant though... – Ogen Mar 30 '15 at 9:46
1

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++;
    }
});
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.