[英]Why can't I use instances of a generic type but can outside?
考慮以下代碼
class SomeClass {
}
class GenericsExample<E extends SomeClass> {
public void createError() {
process(new SomeClass()); //Compiler error!
}
public void createWorking() {
E some = new SomeClass(); //Compiler error!
process(some);
}
public void process(E object) {
}
}
public class Sandbox {
public void run() {
new GenericsExample<SomeClass>().process(new SomeClass()); //Not a compiler error?!
new GenericsExample().process(new SomeClass()); //Still not a compiler error?!
}
}
第一個錯誤的消息(第二個基本上是相同的)
required: E
found: SomeClass
reason: actual argument SomeClass cannot be converted to E by method invocation conversion
where E is a type-variable:
E extends SomeClass declared in class GenericsExample
可以通過將SomeClass強制轉換為E來解決此問題,但是為什么我必須這樣做? 如果某個方法將E作為參數並且E擴展了SomeClass,那么它不應該接受SomeClass作為參數嗎? 為什么這是編譯器錯誤而不是警告?
為什么即使在我什至都不聲明泛型的情況下,這也不適用於外部類? 為什么GenericsExample與Sandbox中的規則如此不同?
E extends SomeClass
正如您剛才所寫, E
與SomeClass
。
您不能將基本類型的實例分配給更多派生類型的變量,就像您不能編寫
Button myButton = new Control(); // Not actually a button!
可以分配給類型的變量唯一E
是類型的實例E
。
在類之外,它僅適用於您使用的是GenericClass<SomeClass>
。 那里, E
是 SomeClass
。
我認為,如果您僅將其交換為更具體的示例,這將變得很清楚。
假設您將E
和SomeClass
交換為Integer
和Number
(請注意,與工具相反的擴展名)是Integer extends Number
。 在這種情況下,很明顯您無法執行以下操作
Integer i = new Number();
因為整數比數字更具體。
為什么即使在我什至都不聲明泛型的情況下,這也不適用於外部類?
因為情況不同:
new GenericsExample<SomeClass>().process(new SomeClass());
這不是編譯器錯誤,因為在這里,您兩邊都有SomeClass
, 而不是 E extends SomeClass
。
new GenericsExample().process(new SomeClass());
而且這甚至沒有使用泛型,因此您選擇不使用泛型類型安全性(並得到有關此問題的編譯器警告)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.