Difference between Bounded Type parameter (T extends) and Upper Bound Wildcard (? extends)

后端 未结 5 1081
余生分开走
余生分开走 2020-12-16 14:18

I know that there was a similar question already posted, although I think mine is somewhat different...

Suppose you have two methods:

// Bounded type         


        
5条回答
  •  旧时难觅i
    2020-12-16 14:53

    There are following three types of Wildcard usually used with Generic in JAVA. Each one is explained as below with example.

    Upper-bounded Wildcard:

    ? extends T : In Upper bounded wildcard only T or its subtypes will be supported. For example we have an Animal class and have Dog , Cat as its subtypes. So following generic methods will only accept parameters of type Data, Data and Data

    public static void add(Data animalData) {
    
    }
    

    Lower-bounded Wildcard:

    ? super T : In Lower-bounded wildcard only T or its super types will be supported. Same example we used for defining Lower-bounded Wildcard. Lets say we have Animal class as super or parent class and Dog as its child class. Now below method use Lower-bounded Wildcard and will only accept parameters of type

    Data, Data and  Data
    
    public static void add(Data animalData) {
    }
    
    
    

    Unbounded Wildcard:

    ? : Unbounded wildcard supports all types. So our above example method can take parameters of type

    Data, Data , Data and Data
    public static void add(Data animalData) {       
    }
    
        

    提交回复
    热议问题