Java泛型-桥接方法 [英] Java generics - bridge method

查看:31
本文介绍了Java泛型-桥接方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当涉及到桥接方法时,我确实知道Java编译器会在需要时添加它们,以便子类可以正确地进行覆盖(在mughal和angelikalanger网站上阅读SCJP之后).但这有点令人困惑,如下所示:

When comes to bridge method, i do know that java compiler will add them if there's a need so that overriding can be done properly by the subclass (after reading SCJP by mughal and angelikalanger website). But this is a bit confusing as per below:

删除之前:

class x <T> {  
   void set(T t){}  
}

class y <E> extends x {  
   void set(E e) {} // name clash here  
}

class z<E> extends x {  
   void set(Object y) {} // no name clash here  
}

class z1<E> extends x<T> {  
   void set(Object y) {} // name clash here  
}

删除后:

class x {  
   void set (Object t) {}  
}

我了解y类的名称冲突,但是为什么z类没有名称冲突?还有类z1的名称冲突吗?令人费解的

I understand the name clash for class y but why there is no name clash for class z? Also there is a name clash for class z1? Puzzling

推荐答案

class y <E> extends x {  
   void set(E e) {} // name clash here  
}

此处发生名称冲突是因为E不是T的子类.因此您不能以这种方式覆盖set方法.请参阅z1的说明以更好地理解.要使y班上班,您必须有

Here name clash occurs because E is not a subclass of T. So you cannot override the set method this way.see the explanation for z1 to understand better. For class y to work, you must have

class y <E> extends x<E> {  
   void set(E e) {}  
}

下一步:

class z<E> extends x {  
   void set(Object y) {} // no name clash here  
}

这里没有名称冲突,因为在类X中,set方法被解释为

Here there is no name clash because in the class X, set method gets interpreted as

void set(java.lang.Object) 

在类z中,set的参数也是java.lang.Object.so,所以不会发生冲突.

and in class z also the parameter of set is java.lang.Object.so no clash.

下一步:

class z1<E> extends x<T> {  
   void set(Object y) {} // name clash here  
}

再次在这里发生名称冲突是因为您必须将x赋予的任何类型参数都作为set的参数.在这里,您传递给x类型参数T,但是您将set方法的参数设置为java.lang.Object.因此名称冲突.

Again here name clash occurs because you have to have as parameter of set whatever type parameter you give to x. here, you pass to x type parameter T, but you have parameter of set method as java.lang.Object. hence name clash.

要使z工作,您必须具有:

For z to work you must have:

class z1<E> extends x<Object> {  
       void set(Object y) {}  
}

这篇关于Java泛型-桥接方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆