implicit upcasting and explicit downcasting in java

和自甴很熟 提交于 2019-12-04 22:01:13

问题


When java can implicitly do up casting , why does not it implicitly do down casting ?Please explain with some simple example?


回答1:


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



来源:https://stackoverflow.com/questions/23042236/implicit-upcasting-and-explicit-downcasting-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!