加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

Java子类化问题与泛型类型的自引用类型

发布时间:2020-12-15 02:31:46 所属栏目:Java 来源:网络整理
导读:import java.util.*;// Let's define a self-referential type:class SelfReferentialT extends SelfReferentialT {}//A complete (i.e. not parameterized) subtype of SelfReferential:class SubclassA extends SelfReferentialSubclassA {}//A partial (i
import java.util.*;

// Let's define a self-referential type:
class SelfReferential<T extends SelfReferential<T>> {}

//A complete (i.e. not parameterized) subtype of SelfReferential:
class SubclassA extends SelfReferential<SubclassA> {}

//A partial (i.e. parameterized) subtype of SelfReferential:
class SubclassB<T extends SubclassB<T>> extends SelfReferential<T> {}

//Two complete subtypes of SubclassB
class SubclassB1 extends SubclassB<SubclassB1> {}    
class SubclassB2 extends SubclassB<SubclassB2> {}

//Now let's define a generic type over SelfReferential:
class Generic<T extends SelfReferential<T>> {}

//No problem creating a subtype for A,B1 or B2
class GenericA extends Generic<SubclassA> {}   
class GenericB1 extends Generic<SubclassB1> {}    
class GenericB2 extends Generic<SubclassB2> {}

//We can also defined a parameterize type for specific types extending SubclassB
class GenericB<T extends SubclassB<T>> extends Generic<T> {}

//However,it does not seem possible to define a non-parameterized subtype of Generic of ANY subtype of SublassB
//My goal is to provide a type alias for GenericB<? extends SubclassB<?>> to avoid 
//having to mention it everywhere in the code. This is like providing an alias for ArrayList<String> using 
class ArrayListOfString extends ArrayList<String> {}

//Unsucessful attempts:
//class GenericAnyB extends Generic<SubclassB> {} //ERROR: bound mismatch
//class GenericAnyB extends Generic<SubclassB<?>> {} //ERROR: bound mismatch
//class GenericAnyB extends Generic<? extends SubclassB<?>> {} //ERROR: invalid syntax: a supertype cannot specify any wildcard
//class GenericAnyB extends Generic<SubclassB<? extends SubclassB>> {} //ERROR: bound mismatch
//class GenericAnyB extends Generic<SubclassB<SubclassB<SubclassB<SubclassB<SubclassB<SubclassB>>>>>> {} // well...
//class GenericAnyB extends <T extends SubclassB<T>> Generic<T> {} //ERROR: this syntax is illegal

最重要的是,我无法在extends子句中指定“引用循环”.

问题:这是Java语言限制吗?

解决方法

你是对的,这是不可能的,就像在没有通配符或原始类型的情况下宣布具有自引用类型的变量一样.您将无法直接实例化SubclassB,原因与您在没有自引用类型参数的情况下不能将其用作绑定的原因相同.

有关此限制的更多讨论,请参阅此帖子:Self bound generic type with fluent interface and inheritance

底线是GenericAnyB本身需要通用才能使用SubclassB作为绑定:

class GenericAnyB<T extends SubclassB<T>> extends Generic<T> { }

在任何可用的东西之前,只需在层次结构中添加额外的步骤:

class GenericB1 extends GenericAnyB<SubclassB1> { }   
class GenericB2 extends GenericAnyB<SubclassB2> { }

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读