我有一个简单的 foo
类,我可以在没有任何编译器的情况下转换为集合接口(interface)(Map
或 List
)错误。
请注意,Foo
类不实现任何接口(interface)或扩展任何其他类。
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
}
}
当我尝试将 Foo
类强制转换为集合时,为什么 Java 编译器不返回 不兼容类型错误?
Foo
没有实现 Collection
。我预计会出现不兼容的类型错误,因为鉴于当前的 Foo
类签名,这不能是 Collection
。
最佳答案
这不是因为它们是集合类,而是因为它们是接口(interface)。 Foo
没有实现它们,但它的子类可以。所以这不是编译时错误,因为这些方法可能对子类有效。在运行时,如果 this
不是实现这些接口(interface)的类,自然是运行时错误。
如果您更改 List<String>
至ArrayList<String>
,你也会得到一个编译器时错误,因为 Foo
子类可以实现 List
,但不能扩展 ArrayList
(因为 Foo
没有)。同样,如果您制作 Foo
final
, 编译器会给你一个错误的接口(interface)转换,因为它知道它们永远不会是真的(因为 Foo
不能有子类,并且不实现这些接口(interface))。
关于java - 为什么 Java 让你强制转换为集合?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52698154/