When java can implicitly do up casting , why does not it implicitly do down casting ?Please explain with some simple example?
Type Casting Types in Java Java Type Casting is classified into two types. Widening Casting (Implicit) – Automatic Type Conversion. Narrowing Casting (Explicit) – Need Explicit Conversion.
What are Upcasting and Downcasting in Java? Upcasting (Generalization or Widening) is casting to a parent type in simple words casting individual type to one common type is called upcasting while downcasting (specialization or narrowing) is casting to a child type or casting common type to individual type.
Typically, the upcasting is implicitly performed by the compiler. Upcasting is closely related to inheritance — another core concept in Java. It's common to use reference variables to refer to a more specific type. And every time we do this, implicit upcasting takes place.
Upcasting: Upcasting is the typecasting of a child object to a parent object. Upcasting can be done implicitly. Upcasting gives us the flexibility to access the parent class members but it is not possible to access all the child class members using this feature.
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!"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With