简体   繁体   English

java中的隐式向上转换和显式向下转换

[英]implicit upcasting and explicit downcasting in java

当java可以隐式地进行转换时,为什么不隐式地进行转换?请用一些简单的例子来解释一下?

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

But: 但:

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!" 因为这是一个“危险”的操作,语言迫使你明确地做 - 你基本上是对编译器说“我知道的比你现在做的更多!”

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM