简体   繁体   English

Java中的通用方法,语法

[英]Generic method in Java, syntax

What is happening in line 6? 第6行发生了什么? <C extends Cat> is the return type of useMe, right? <C extends Cat>是useMe的返回类型,对吧? What does <? super Dog> 什么<? super Dog> <? super Dog> do? <? super Dog>吗?

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 . <C extends Cat>指定useMe有一个通用参数C ,它必须扩展Cat

Its return type is Mixer<? super Dog> 它的返回类型是Mixer<? super Dog> 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. 第一个通用参数规范<C extends Cat>使useMe成为使用参数C参数化的通用方法,参数C来自CatCat本身。

The second generic parameter specification <? super Dog> 第二个通用参数规范<? 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. <? super Dog>指的是方法的返回类型,它是一个参数化的Mixer ,其中唯一的泛型参数是DogDog类本身的超类。

Thus, line 6 means: useMe is a generic method parametrized with C deriving from Cat (or being Cat itself). 因此,第6行意味着: useMe是一个通用方法,使用从Cat (或Cat本身)派生的C参数化。 The method takes two arguments of types A and C and returns type Mixer parametrized with a super-type of Dog (possibly Dog itself). 该方法采用AC类型A两个参数,并返回类型Mixer参数化的超类型Dog (可能是Dog本身)。

<C extends Cat> is NOT the return type. <C extends Cat>不是返回类型。 Mixer<? super Dog> Mixer<? super Dog> is. Mixer<? super Dog>是。 The former is only specified to specify the type of c. 前者仅指定用于指定c的类型。

No, the return type is Mixer<? super Dog> 不,返回类型是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 Mixer<? super Dog> ,方法本身是一个泛型方法,它使用泛型参数C ,可以扩展Cat任何类,并用作参数C c

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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