gpt4 book ai didi

java - 如何纠正? -- "both define getObjectCopy(), but with unrelated return types"-- 但它是*一个*函数

转载 作者:行者123 更新时间:2023-12-02 06:16:40 24 4
gpt4 key购买 nike

我有以下接口(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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com