扩展Generic父级时的值转换

时间:2014-08-04 01:39:56

标签: java generics inheritance

为什么子类仍然需要转换来访问其Generic父级属性的值?任何特殊原因?看看:

    class a<U, T> {    

    public U u;   
    public T t;    
    public a(U u, T t) {
        this.u = u;
        this.t = t;            
    }

    public U getU(){
         return u;
     }   
   }


class b extends a { 
    public b(String u, Integer t) { super(u, t); }


     // Here I call b's parent method where casting occurs
    public String get(){
    return (String) getU(); // Here's the cast
    }
}

我知道super.getU()返回的类型是U,但不是b继承自a,这意味着a的属性将是它的儿童课可见!?加上superclass的构造函数已被super(11111,“aString”)引用; ?告诉b的父母“我是你的孩子通过Integer&amp; a String”是不够的,它让我觉得课间没有任何关系“a”和“b”类

* UDPATE :代码拼写错误已修复,抱歉发生这种情况因为我输入的时间很快。

2 个答案:

答案 0 :(得分:3)

编辑后,问题是您在extends声明中使用了原始类型。

class b extends a {

使用原始类型时,例如a,将删除所有类型参数。调用父类时#39; getU()方法,返回类型被删除到其上限,从UObject. Your subclass method has a return type of String , but you attempt to return an Object`。这就是演员必要的原因。

What is a raw type and why shouldn't we use it?

不要使用原始类型。参数化您的类型用法并且案例不是必需的..

class b extends a<String, Integer> {

    public b(String u, Integer t) {
        super(u, t);

    }    

    public String get() {
        return getU();  
    }
}

答案 1 :(得分:2)

正如您所料,无需投射

我认为你的实际问题是当你这样做时:

B extends A<String, Integer>

......知道:

class A<U, T>

...然后UStringTInteger。因此,您的方法B#callGetU()应返回String,而不是Integer。 ;)


以下是您的B课程应如何显示的示例:

class B extends A<String, Integer> {

    public B(final String u, final Integer t) {  // <- Swapped Integer and String
        super("aString", 11111); // <- Swapped 11111 and "aString"
    }

    // Here I call b's parent method here where casting occurs
    public String callGetU() {   // <- U is String, not Integer
        return getU();           // <- Removed unnecessary cast
    }
}