简体   繁体   English

Java泛型 - 构造函数类型

[英]Java generics- constructor type

public class AClass<X extends AnInterface>{

    public AClass(X x){
    }

}

public class Y implements AnInterface{

}

In the calling code if I have: 在调用代码中,如果我有:

public static<X extends AnInterface> void main(String args){

    AnInterface y = new Y();
    AClass a = new AClass<AnInterface>(y);

}

I should be able to get this to work using X in the constructor for AClass right? 我应该能够在AClass的构造函数中使用X来实现这一点吗? I am getting errors telling me the contructor for AClass should be of type AnInterface?? 我收到错误告诉我AClass的构造函数应该是AnInterface类型?

EDITED to change AClass a = new AClass<AnInterface>(y); EDITED改变AClass a = new AClass<AnInterface>(y);

You need to tell AClass what type its expecting. 你需要告诉AClass它的期望类型。

    public static void main(String args){
        AnInterface y = new Y();
        AClass<AnInterface> a = new AClass<AnInterface>(y);
    }
public static void main(String[] args) {
    AnInterface y = new Y();
    AClass a = new AClass(y);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM