Generics in Java, using wildcards

前端 未结 2 531
梦毁少年i
梦毁少年i 2021-01-06 07:02

I have a question about Generics in Java, namely using wildcards. I have an example class GenClass like this:

public class GenClass {

    private E         


        
2条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-01-06 07:38

    mmyers has the correct answer, but I just wanted to comment on this part of your question (which sounds like your rationale for wanting to use the wildcard):

    I thought that the way I have used the wildcard, makes the reference variable c be of type GenClass, which would accept as parameter any class - on the place of E I would have any class. This is just the declaration of the variable. Then I initialize it with

    If you really want to accomplish this, you could do something like without compilation errors:

    GenClass gc = new GenClass();
    gc.setVar(new ExampleClass());
    
    
    

    But then again, if you want to declare an instance of GenClass that can contain any type, I'm not sure why you'd want to use generics at all - you could just use the raw class:

    GenClass raw = new GenClass();
    raw.setVar(new ExampleClass());
    raw.setVar("this runs ok");
    

    提交回复
    热议问题