Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/325.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/79.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 协变返回或泛型_Java_Inheritance_Casting_Covariance - Fatal编程技术网

Java 协变返回或泛型

Java 协变返回或泛型,java,inheritance,casting,covariance,Java,Inheritance,Casting,Covariance,我希望在接口中有一个方法,该方法返回一个类型未在包中定义的类。然后,实现类将返回特定类型。我可以看到至少3种方法如何做到这一点,如下所示为fn1、fn2和fn3。在所有情况下,都存在某种形式的未经检查的强制转换。这些方法中有哪一种是首选的?还是有更好的?假设接口I1和方法dostuff位于其他jar包中,并且没有对测试或Integer类的访问权 您不能在接口中使用泛型吗?像 public interface I1<T> { T fn1(); // etc } 当

我希望在接口中有一个方法,该方法返回一个类型未在包中定义的类。然后,实现类将返回特定类型。我可以看到至少3种方法如何做到这一点,如下所示为fn1、fn2和fn3。在所有情况下,都存在某种形式的未经检查的强制转换。这些方法中有哪一种是首选的?还是有更好的?假设接口I1和方法dostuff位于其他jar包中,并且没有对测试或Integer类的访问权


您不能在接口中使用泛型吗?像

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
}