Java 协变返回或泛型
我希望在接口中有一个方法,该方法返回一个类型未在包中定义的类。然后,实现类将返回特定类型。我可以看到至少3种方法如何做到这一点,如下所示为fn1、fn2和fn3。在所有情况下,都存在某种形式的未经检查的强制转换。这些方法中有哪一种是首选的?还是有更好的?假设接口I1和方法dostuff位于其他jar包中,并且没有对测试或Integer类的访问权Java 协变返回或泛型,java,inheritance,casting,covariance,Java,Inheritance,Casting,Covariance,我希望在接口中有一个方法,该方法返回一个类型未在包中定义的类。然后,实现类将返回特定类型。我可以看到至少3种方法如何做到这一点,如下所示为fn1、fn2和fn3。在所有情况下,都存在某种形式的未经检查的强制转换。这些方法中有哪一种是首选的?还是有更好的?假设接口I1和方法dostuff位于其他jar包中,并且没有对测试或Integer类的访问权 您不能在接口中使用泛型吗?像 public interface I1<T> { T fn1(); // etc } 当
您不能在接口中使用泛型吗?像
public interface I1<T> {
T fn1();
// etc
}
当你提到T时,就不需要浇铸了
至少我喜欢这样。当然,您还可以指定希望使用的内容
<T extends myInterface>
您不能在接口中使用泛型吗?像
public interface I1<T> {
T fn1();
// etc
}
当你提到T时,就不需要浇铸了
至少我喜欢这样。当然,您还可以指定希望使用的内容
<T extends myInterface>
我会这样做的
public interface I1<T> {
T fn1();
}
public class Test implements I1<Integer> {
@Override
public Integer fn1() {
return new Integer(1);
}
}
public static void main(String[] args) {
Myclass c = new Myclass();
I1<Integer> t = c.new Test();
Integer i = t.fn1(); <-- no cast
}
我会这样做的
public interface I1<T> {
T fn1();
}
public class Test implements I1<Integer> {
@Override
public Integer fn1() {
return new Integer(1);
}
}
public static void main(String[] args) {
Myclass c = new Myclass();
I1<Integer> t = c.new Test();
Integer i = t.fn1(); <-- no cast
}