简体   繁体   中英

Generic method in Java, syntax

What is happening in line 6? <C extends Cat> is the return type of useMe, right? What does <? super Dog> <? super Dog> do?

2. class Animal { }
3. class Dog extends Animal { }
4. class Cat extends Animal { }
5. public class Mixer<A extends Animal> {
6. public <C extends Cat> Mixer<? super Dog> useMe(A a, C c) {
7. //Some code
8. } }    

The <C extends Cat> specifies that useMe has one generic parameter, C , which must extend Cat .

Its return type is Mixer<? super Dog> Mixer<? super Dog> . The ? denotes a wildcard .

The first generic parameter specification <C extends Cat> makes useMe a generic method parametrized with parameter C which derives from Cat or is Cat itself.

The second generic parameter specification <? super Dog> <? super Dog> refers to the method's return type which is a parametrized Mixer where the sole generic parameter is a super class of Dog or Dog class itself.

Thus, line 6 means: useMe is a generic method parametrized with C deriving from Cat (or being Cat itself). The method takes two arguments of types A and C and returns type Mixer parametrized with a super-type of Dog (possibly Dog itself).

<C extends Cat> is NOT the return type. Mixer<? super Dog> Mixer<? super Dog> is. The former is only specified to specify the type of c.

No, the return type is Mixer<? super Dog> Mixer<? super Dog> , and the method itself is a generic method which uses a generic parameter C , which can any class that extends Cat , and is used as a parameter C c

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