本文介绍了Java 中是否存在用于满足接口的空方法的习语?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个类 Foo 实现了一个接口,例如 MouseListener.MouseListener 接口由五个方法组成,但我只想覆盖其中一个(mouseClicked()).是否有一种标准的、惯用的方式来格式化其他方法?

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?

我倾向于写以下内容:

@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) {}

我通常对此没有意见,我理解作者的意图,但是当 (推荐) @Override 注释被添加.

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.

我不是一个特别有经验的 Java 编码员,所以我想我会问是否有约定.想法?

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

推荐答案

在这种特殊情况下,您应该遵循 wilums2 的建议并扩展 MouseAdapter 而不是实现 MouseListener.这些适配器类的目的是让您在只实现接口的某些方法时不必提供空的实现.

In this particular case you should follow wilums2's advice and extend MouseAdapter instead of implementing MouseListener. The purpose of these adapter classes is so that you don't have to provide empty implementations when you're only implementing some of the methods of an interface.

更一般地说,简短的回答是不",没有关于如何记录空方法的标准约定,尽管我通常使用类似

More generally, the short answer is 'no', there is no standard convention for how to document empty methods, though I generally use something like

@Override
void foo() {
  // No implementation necessary
}

这篇关于Java 中是否存在用于满足接口的空方法的习语?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-03 20:06