Number945
Number945

Reputation: 4940

implicit upcasting and explicit downcasting in java

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

Upvotes: 9

Views: 6970

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1500875

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

Upvotes: 15

Related Questions