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

使用Generic Interface的Generic类编译失败

发布时间:2020-12-15 04:40:11 所属栏目:Java 来源:网络整理
导读:据我所知,下面的代码应该运行,没有任何编译错误. 但是,当我运行此程序时,我得到以下编译错误. The member type B.D cannot be qualified with a parameterized type, since it is static. Remove arguments from qualifying type B class BX { interface C {
据我所知,下面的代码应该运行,没有任何编译错误.

但是,当我运行此程序时,我得到以下编译错误.

The member type B.D cannot be qualified with a parameterized type,
since it is static. Remove arguments from qualifying type B

class B<X> {
    interface C {
    }

    interface D<Y> {
    }
}

class Test {
     // compilation fails here
    B<String>.D<String>[] arr = new B<String>.D<String>[10];
}

请帮我理解这个行为.

解决方法

在类似于内部静态类的方式中,嵌套接口与其外部类的实例没有关联,只与该类本身有关联.无论B的类型参数如何,所有静态成员都在B的所有实例之间共享.考虑:

class B<T> {
    public static int shared = 0;
}

变量共享在B< String>,B< Integer>,B< Object>中是相同的.等等.尝试在参数化B上访问它会导致编译错误:

int copy = B<String>.shared; // <<== Does not compile

因此,B的类型参数对arr的声明没有影响,所以Java要你删除它:

B.D<String>[] arr = new B.D[10];

(编辑:李大同)

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

    推荐文章
      热点阅读