为什么Java让您强制转换为集合? [英] Why does Java let you cast to a collection?
问题描述
我有一个简单的 foo
类,并且能够转换为集合接口( Map
或列表
)而没有任何编译器错误。
请注意, Foo
类不会实现任何接口或扩展任何其他类。
I have a simple foo
class, and I am able to cast to a collection interface (either Map
or List
) without any compiler error.
Note that Foo
class does not implement any interface or extends any other class.
public class Foo {
public List<String> getCollectionCast() {
return (List<String>) this; // No compiler error
}
public Map<String, String> getCollection2Cast() {
return (Map<String, String>) this; // No compiler error
}
public Other getCast() {
return (Other)this; // Incompatible types. Cannot cast Foo to Other
}
public static class Other {
// Just for casting demo
}
}
为什么当我尝试投射<时,Java编译器为什么不返回 incompatible types error ? code> Foo 类到集合吗?
Why does the Java compiler not return incompatible types error when I try to cast the Foo
class to a collection?
Foo
未实现集合
。我会期望出现不兼容的类型错误,因为给定当前的 Foo
类签名,所以它不能是 Collection
。
Foo
does not implement Collection
. I would expect an incompatible types error, because given the current Foo
class signature, this cannot be a Collection
.
推荐答案
不是因为它们是集合类,而是因为它们是接口。 Foo
不会实现它们,但可以实现它的子类。因此,这不是编译时错误,因为这些方法可能对子类有效。在运行时,如果这个
不是实现那些接口的类,则自然是运行时错误。
It's not because they're collection classes, it's because they're interfaces. Foo
doesn't implement them, but subclasses of it could. So it's not a compile-time error, since those methods may be valid for subclasses. At runtime, if this
isn't of a class that implements those interfaces, naturally it's a runtime error.
如果将 List< String>
更改为 ArrayList< String>
,您将得到同样,这也是一个编译时错误,因为 Foo
子类可以实现 List
,但不能扩展 ArrayList
(因为 Foo
没有)。同样,如果您使 Foo
final
,则编译器将为您的接口类型转换提供错误,因为它知道它们可以永远都不是真的(因为 Foo
不能有子类,并且不能实现那些接口)。
If you change List<String>
to ArrayList<String>
, you'll get a compiler-time error for that, too, since a Foo
subclass could implement List
, but can't extend ArrayList
(since Foo
doesn't). Similarly, if you make Foo
final
, the compiler will give you an error for your interface casts because it knows they can never be true (since Foo
can't have subclasses, and doesn't implement those interfaces).
这篇关于为什么Java让您强制转换为集合?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!