这有点难以解释,但我到处都找过了,但找不到任何好的答案。
我还看到了 Stack Overflow 的问题如何引用 Java 中接口实现的类类型? https://stackoverflow.com/questions/8161712/how-can-i-refer-to-the-class-type-a-interface-is-implementing-in-java and 如何返回与使用 Java 6 传入的类相同类型的对象实例? https://stackoverflow.com/questions/9790908/how-do-i-return-an-instance-of-an-object-of-the-same-type-as-the-class-passed-in,但他们无法回答我的问题。当我应用继承时有一个例外。
举个例子,方便大家理解:
假设我有一些名为 SelfMaker 的界面:
public interface SelfMaker <SELF>{
public SELF getSelf();
}
A 有一只狗,它可以与另一只狗繁殖。所以这只狗是一个“自我创造者”,就像这样:
public class Dog implements SelfMaker<Dog> {
String color;
public String toString() {
return "some " + color + " dog";
}
public Dog procreate(Dog anotherDog) {
Dog son = getSelf();
son.color = color;
return son;
}
@Override
public Dog getSelf() {
return new Dog();
}
}
但是,我有一只家养狗,它是一只狗,但它有一个可爱的家庭给它命名。像这样:
public class DomesticDog extends Dog {
private String name;
public String toString() {
return super.toString() + " named " + name;
}
}
现在,我有一些类可以处理一些“SelfMaker”的事情,我们称这个类为“Couple”。像这样:
public class Couple<T extends SelfMaker<T>> {
private T first;
private T second;
public String toString() {
return first.toString() + " and " + second.toString();
}
}
例外:
当我想创建几个时例外DomesticDog
s。像这样:
public class CoupleOfDomesticDogs extends Couple<DomesticDog>{
public DomesticDog procreate(){
DomesticDog son = first.procreate(second);
return son;
}
}
这将引发异常<DomesticDog>
抱怨:Bound mismatch: The type DomesticDog is not a valid substitute for the bounded parameter <T extends SelfMaker<T>> of the type Couple<T>
我已经尝试将广义变量从 Couple 类更改为:Couple<T extends SelfMaker<?>>
但“儿子”不会是DomesticDog(我希望“儿子”是DomesticDog)。如果我添加一些强制转换,那么它会编译,但会不太清晰。
所以...这里的问题是:有没有一种方法可以在不进行强制转换和泛化的情况下实现这一目标?