[英]Why is it that a generic type can be defined for a static method only?
Book, Introduction to Java Programming, says, "A generic type can be defined for a static method." 《 Java编程简介》一书中说:“可以为静态方法定义通用类型。” Why instance methods can't be generic? 为什么实例方法不能通用?
Instance methods can be generic. 实例方法可以是通用的。 The following code compiles with Java 5 and later. 以下代码使用Java 5及更高版本进行编译。 As you can see, I have defined a generic instance method and a generic static method in the same way. 如您所见,我以相同的方式定义了通用实例方法和通用静态方法。
package com.company;
public class Generics {
public <T> T returnAGenericType(T returnThisOne) {
return returnThisOne;
}
public static <T> T returnAGenericTypeStatic(T returnThisOne) {
return returnThisOne;
}
}
ArrayList::toArray
, ArrayList::get
and ArrayList::set
are all examples of instance methods with generic type parameters. ArrayList::toArray
, ArrayList::get
和ArrayList::set
都是具有泛型类型参数的实例方法的示例。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.