<T延伸是什么意思?

我见过如下所示的方法:

protected  T save( T Acd, boolean en) { 

它有什么作用? 在Java中调用的这些类型的方法声明是什么?

它被称为通用方法。 这整个概念在Java中称为“generics”。 该声明意味着T可以是ABC的子类的任何类型。

有界类型参数:

有时您可能希望限制允许传递给类型参数的类型。 例如,对数字进行操作的方法可能只想接受Number或其子类的实例。 这是有界类型参数的用途。

要声明有界类型参数,请列出类型参数的名称,然后是extends关键字,后跟其上限。 例:

下面的示例说明了扩展在一般意义上如何用于表示“扩展”(如在类中)或“实现”(如在接口中)。 此示例是返回三个Comparable对象中最大的对象的Generic方法:

 public class MaximumTest { // determines the largest of three Comparable objects public static > T maximum(T x, T y, T z) { T max = x; // assume x is initially the largest if ( y.compareTo( max ) > 0 ){ max = y; // y is the largest so far } if ( z.compareTo( max ) > 0 ){ max = z; // z is the largest now } return max; // returns the largest object } public static void main( String args[] ) { System.out.printf( "Max of %d, %d and %d is %d\n\n", 3, 4, 5, maximum( 3, 4, 5 ) ); System.out.printf( "Maxm of %.1f,%.1f and %.1f is %.1f\n\n", 6.6, 8.8, 7.7, maximum( 6.6, 8.8, 7.7 ) ); System.out.printf( "Max of %s, %s and %s is %s\n","pear", "apple", "orange", maximum( "pear", "apple", "orange" ) ); } } 

这意味着您必须发送ABC对象或ABC的子级,不允许其他类。 此外,您的Acd变量可以使用ABC类中的方法,这些方法对于包含save方法的类是可见的。

T类扩展接口时,这很有用。 例如,您正在创建一个处理对象数组排序的类,该类必须实现Comparable接口,否则将不允许该数组:

 class Class1 implements Comparable { //attributes, getters and setters... int x; //implementing the interface... public int compareTo(Class1 c1) { //nice implementation of compareTo return (this.x > c1.x)? 1 : (this.x < c1.x) ? 0 : -1; } } class Class2 { int x; } public class Sorter> { public static void insertionSort(T[] array) { //good implementation of insertion sort goes here... //just to prove that you can use the methods of the Comparable interface... array[0].compareTo(array[1]); } public static void main(String[] args) { Class1[] arrC1 = new Class1[5]; Class2[] arrC2 = new Class2[5]; //fill the arrays... insertionSort(arrC1); //good! insertionSort(arrC2); //compiler error! } } 

这是一个省略参数T和布尔类型的save method ,其中T必须由ABC Class上限。 ABC类或任何子类将被接受。

这在Java中称为generics。

官方解释:简而言之,generics使类型(类和接口)在定义类,接口和方法时成为参数。 与方法声明中使用的更熟悉的forms参数非常相似,类型参数为您提供了一种使用不同输入重用相同代码的方法。 不同之处在于forms参数的输入是值,而类型参数的输入是类型。

非正式:像Java这样的强类型语言会导致更多错误出现在编译时而不是运行时。 这是件好事。 但它会导致代码重复。 为了缓解这种generics,Java被添加到了Java中。

这是generics。 类型边界的generics!

请参阅此处以获取参考