首页 > 解决方案 > 将泛型对象作为父子对象中的方法参数传递 - 整数不能转换为 E

问题描述

这是我的情况,我无法让它工作。

public class A<E extends Comparable<E>> {

    E e;
    void setE(E e1){ 
        e = e1; 
     }
}

public class main{

      public static void main(String[] args){

              A<Integer> aObj = new A<Integer>

              aObj.setE(some_e);  // works perfectly

              C cObj = new C();

             // this is what I want to do or something similar but it doesnt work because of the failure shown below
             cObj.readSomeFileToGetE(aObj); 

     }

但是我有另一个真正需要设置 E 而不是 main 的类(因为它读取一个文件并且有很多方便的相关代码),它的父子层次结构如下:

public class B{

     public <E extends Comparable<E>> void readSomeFileTogetE(A<E>);

}

public class IntB extends B() {

   //This derived class will only cater to Integers. Similar sibling classes will cater to Floats, etc.

    public <E extends Comparable<E>> void readsomeFileTogetE(A<E> aObj){

           //buffered reader defined to read a file that store an integer
           String xyz = br.readline();

           Integer some_e = Integer.parseInt(xyz);

           aObj.setE(some_e); // fails saying Integer cannot be converted to E. 

    }

}

公共类 FloatB 扩展 B() {

   //This derived class will only cater to Floats. 

    public <E extends Comparable<E>> void readsomeFileTogetE(A<E> aObj){

           //buffered reader defined to read a file that store an integer
           String xyz = br.readline();

           Integer some_e = Float.parseFloat(xyz);

           aObj.setE(some_e); // will fail as well. 

    }

}

本质上,我必须将一个通用对象作为参数传递给子类。

我来自一个 C 编程世界,在那里传递 void 似乎更容易,但在 Java 中,强类型语法使它变得更加困难。

是否可以用 Java 做我计划做的事情?任何帮助表示赞赏。谢谢。

标签: javagenericsinheritance

解决方案


推荐阅读