且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2022-12-15 12:50:17

关键是,向上转换总会成功,所以它是安全的 - 而向下转换可能会失败:

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!"