gpt4 book ai didi

java - 实现实现接口(interface)的类的复制方法 - Java

转载 作者:行者123 更新时间:2023-11-30 10:10:32 24 4
gpt4 key购买 nike

我遇到了这种奇怪的情况,我有一个实现接口(interface) TheInterface 的类 TheClass,而类 TheClass 应该有一个返回类型为 TheInterface 的 copy() 方法,它应该对自己进行浅拷贝。尝试调用我的函数 copy() 并使用它时,出现不兼容类型错误。我需要保持 copy() 方法的返回类型不变。

有什么方法可以做到这一点吗?

谢谢

class TheClass implements TheInterface,Cloneable {


private Set<Integer> set;

public TheClass(){
set=new HashSet<Integer>();
}

public TheInterface copy() {
TheInterface clone = this.clone();
return clone;
}

protected A clone(){
A clone;
try
{
clone = (A) super.clone();
}
catch (CloneNotSupportedException e)
{
throw new Error();
}
return clone;
}

这里我得到了不兼容的类型错误

public class Main  {
public static void main(String[] args) {
TheClass class1 = new TheClass();
TheClass class2 = class1.copy();

最佳答案

部分改进可能是让 TheClass 中的 copy() 返回 TheClass,而接口(interface)中的方法仍然返回 TheInterface 。这是允许的,因为返回类型不是 Java 方法签名的一部分。

这样,你可以做到

TheClass class1 = new TheClass();
TheClass class2 = class1.copy();

但是,如果您在(静态)类型 TheInterface 的变量上调用 copy(),您仍然必须将其分配给 TheInterface (但这似乎合乎逻辑):

TheInterface class1 = new TheClass();
TheInterface class2 = class1.copy(); // cannot be TheClass in this case

关于java - 实现实现接口(interface)的类的复制方法 - Java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52785904/

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