简体   繁体   中英

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? I am getting errors telling me the contructor for AClass should be of type AnInterface??

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

You need to tell AClass what type its expecting.

    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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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