Naman
Naman

Reputation: 2373

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> 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. } }    

Upvotes: 2

Views: 715

Answers (4)

Adam Zalcman
Adam Zalcman

Reputation: 27233

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> 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).

Upvotes: 3

apines
apines

Reputation: 1262

No, the return type is 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

Upvotes: 3

stryba
stryba

Reputation: 2027

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

Upvotes: 2

Oliver Charlesworth
Oliver Charlesworth

Reputation: 272507

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

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

Upvotes: 3

Related Questions