9

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

Number945
  • 4,631
  • 8
  • 45
  • 83

1 Answers1

15

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

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • So what if exceptions are generated ? We can handle exceptions also. – Number945 Apr 13 '14 at 11:40
  • @BreakingBenjamin: Yes, you can - but the point is that you're telling the compiler that you're *aware* that it might happen. If you want to use a language which lets you play more fast and loose without compile-time checking, use a dynamic language such as Python or Ruby. – Jon Skeet Apr 13 '14 at 11:43
  • Another point: the reason you are telling the compiler this is so the compiler doesn't say "you can't do that". I regard this as part of being a strongly-typed language; you are telling the compiler not to generate an error or warning at this point as it normally would. And those of us that want a strongly-typed language do not want that default feature disabled in general, only for those (hopefully few) cases where we need to cast. – arcy Apr 13 '14 at 13:38
  • Another way of looking at it; since the derived class is always a special case of the superclass, then treating your object as a member of the superclass is not ever incorrect. But if you have a superclass object and you want to treat it as a subclass, then it MIGHT be incorrect, so the compiler will flag it unless you cast. – arcy Apr 13 '14 at 13:39