Is there an idiom in Java for empty methods which exist to satisfy an interface?

camdez picture camdez · May 19, 2009 · Viewed 15.8k times · Source

Let's say I have a class Foo implementing an interface such as MouseListener. The MouseListener interface consists of five methods but I only wish to override one of them (mouseClicked()). Is there a standard, idiomatic way of formatting the other methods?

My inclination was to write the following:

@Override
public void mouseClicked(MouseEvent e) {
    // (...) <-- actual code here
}

@Override
public void mouseEntered(MouseEvent e) {
    // Do nothing.  Exists to satisfy MouseListener interface.
}

@Override
public void mouseExited(MouseEvent e) {
    // Do nothing.  Exists to satisfy MouseListener interface.
}

@Override
public void mousePressed(MouseEvent e) {
    // Do nothing.  Exists to satisfy MouseListener interface.
}

@Override
public void mouseReleased(MouseEvent e) {
    // Do nothing.  Exists to satisfy MouseListener interface.
}

I'm a fan of making it explicit that methods are intentionally blank rather than accidentally left so, but I'm not crazy about all the vertical space given up for basically nothing. I've also seen the following format:

public void mouseClicked(MouseEvent e) {
    // (...) <-- actual code here
}

public void mouseEntered(MouseEvent e) {}
public void mouseExited(MouseEvent e) {}
public void mousePressed(MouseEvent e) {}
public void mouseReleased(MouseEvent e) {}

I'm generally OK with this and I understand the author's intent, but it gets really ugly when the (recommended) @Override annotations are added.

I'm not a particularly experienced Java coder so I figured I'd ask if there was a convention. Thoughts?

Answer

Jan Gressmann picture Jan Gressmann · May 19, 2009

I do it the same way you do, if theres nothing there leave at one line. Maybe put a comment on top of a large block of 'implementation one-liners'.