Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 427
Number945 Avatar asked Apr 13 '14 11:04

Number945


People also ask

What is explicit casting and implicit casting in Java?

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 is the difference between Upcasting and downcasting in Java?

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.

Is Upcasting Implicit in Java?

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.

What is implicit Upcasting?

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.


1 Answers

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

like image 74
Jon Skeet Avatar answered Sep 18 '22 09:09

Jon Skeet