java中的隐式向上转换和显式向下转换 [英] implicit upcasting and explicit downcasting in java
问题描述
当java可以隐式执行转换时,为什么不隐式执行转换?请用一些简单的例子来解释一下?
When java can implicitly do up casting , why does not it implicitly do down casting ?Please explain with some simple example?
推荐答案
关键是,向上转换总会成功,所以它是安全的 - 而向下转换可能会失败:
The point is that upcasting will always succeed, so it's safe - whereas downcasting can fail:
String x = getStringFromSomewhere();
Object y = x; // This will *always* work
但是:
Object x = getObjectFromSomewhere();
String y = (String) x; // This might fail with an exception
因为这是一个危险的操作,语言强迫你明确地做 - 你基本上是对编译器说我知道的比你现在做得更多!
Because it's a "dangerous" operation, the language forces you to do it explicitly - you're basically saying to the compiler "I know more than you do at this point!"
这篇关于java中的隐式向上转换和显式向下转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!