我有一个界面,有 20 多个方法,但只有少数对我的需要有意义。我已经实现了所需的方法。
我不想将代码编写为空正文。有没有任何注释或任何方法可以绕过这个并避免编写空白正文?
谢谢。 普拉文
最佳答案
一种选择是让每个未实现的方法抛出UnsupportedOperationException
。这就是 Collections.unmodifyingList()
所做的事情,以便它可以返回 List
但您不能对其使用 add()
。
例如:
@Override
public void notNeeded() {
throw new UnsupportedOperationException();
}
另一个选择是考虑实现这样的接口(interface)是否真的有意义。相反,您可以创建一个更小、更专业的界面,更适合您的用例。如果您可以修改当前接口(interface),请使其扩展新接口(interface),这样就不会收到重复的代码。
例如,假设您有 BigInterface
,它声明了一些您不想在类 MyClass
中实现的方法:
interface BigInterface {
void notNeeded();
int alsoNotNeeded();
boolean neededMethod();
}
您可以仅提取所需的方法并创建一个新接口(interface):
interface SmallInterface {
boolean neededMethod();
}
然后使 BigInterface
扩展 SmallInterface
,以便那些实现 BigInterface
的类继续正常工作:
interface BigInterface extends SmallInterface {
void notNeeded();
int alsoNotNeeded();
}
并让 MyClass
仅实现 SmallInterface
:
class MyClass implements SmallInterface {
@Override
public boolean neededMethod() {
return true;
}
}
关于java - 注释来解决接口(interface)未实现方法的所有错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29453753/