- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我有以下接口(interface)层次结构(删除了所有不相关的功能)。我在尝试编译时收到此错误:
types ValidLineGettable and ValidateValue<java.lang.String> are incompatible; both define getObjectCopy(), but with unrelated return types
这都是从同一个函数派生的——不是两个同名的不同函数,同一个接口(interface)中的同一个函数。您如何处理必须从两个不同接口(interface)继承的接口(interface),而本身必须从单个基接口(interface)继承?
我发现了两个关于恰好具有相同名称的不同函数的问题
就我而言,无论是概念上还是名称上,它都是相同的函数。
(尽管我对 Copyable
接口(interface)是否是一个好主意的意见感兴趣......它在我使用的很多代码中,并且对我来说效果很好...我最感兴趣的是一般继承/设计问题。)
我不清楚如何最好地处理这个问题。我将不胜感激任何建议。谢谢。
public interface Copyable {
Copyable getObjectCopy();
}
interface ValidateValue<O> extends Copyable {
//Other functions...
@Override
ValidateValue<O> getObjectCopy();
}
//For classes that may be able to be Decorated into a TextLineValidator
interface ValidLineGettable extends Copyable {
//Other functions...
ValidLineGettable getObjectCopy();
}
interface TextLineValidator extends ValidateValue<String>, ValidLineGettable {
//Other functions...
@Override
TextLineValidator getObjectCopy();
}
错误:
C:\java_code\Copyable.java:17: types ValidLineGettable and ValidateValue<java.lang.String> are incompatible; both define getObjectCopy(), but with unrelated return types
interface TextLineValidator extends ValidateValue<String>, ValidLineGettable {
^
1 error
Tool completed with exit code 1
最佳答案
假设所有返回值都扩展Copyable
,让所有版本的 getObjectCopy() 返回 Copyable。例如:
public interface ValidateValue<O> extends Copyable
{
// Other functions...
@Override
Copyable getObjectCopy();
}
public Blammy implements ValidateValue<String>
{
// Other functions...
@Override
public Copyable getObjectCopy()
{
SomethingThatExtendsCopyable blammy = new SomethingThatExtendsCopyable();
return (Copyable)blammy;
}
}
在上面的代码中,错误是由于“getObjectCopy”方法在 ValidateValue<String>
中具有不同的返回值而引起的。和ValidLineGettable
接口(interface),但调用签名是相同的。在java中,仅仅改变返回值并不能获得多态性;这会导致编译错误。
如果将返回值更改为Copyable
然后TextLineValidator
不再通过扩展其父接口(interface)来获得值(value)。一种更简单的方法是拥有一个接口(interface)(Copyable)和实现该接口(interface)的多个类,每个类返回一个 Copyable 值,该值可能是扩展(或实现)Copyable 的类的实例。
关于java - 如何纠正? -- "both define getObjectCopy(), but with unrelated return types"-- 但它是*一个*函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21388479/
(这是我的 previous question 的后续。) 我有一个名为Copyable 的接口(interface),它只有一个函数 Copyable getObjectCopy(); 这被许多其他
我有以下接口(interface)层次结构(删除了所有不相关的功能)。我在尝试编译时收到此错误: types ValidLineGettable and ValidateValue are incom
我是一名优秀的程序员,十分优秀!