I realize that upcasting converts subclass to superclass while downcasting does so in opposite way. However, assuming there are different numbers of data types for subclass and superclass, does conversion from subclass->superclass->subclass makes part of data erase because some parts of data inside subclass is not included in superclass?
Because I know that floating points is erased when float types of data gets converted to int in c++, I am wondering if it works the same way for the class in java.
In Java, object types are reference types, meaning that an expression never actually evaluates to an object, only to a reference to an object.
As a result, upcasting and downcasting don't actually touch the object at all; they just give you references of different types to the object.
That is, this Java code:
(Subclass)((Superclass) instanceOfSubclass)
is roughly analogous to this C++ code:
dynamic_cast<subclass &>(static_cast<superclass &>(instance_of_subclass))
However, if you do conversions with value types such as int
and float
, then you can indeed lose data; this Java code:
(double)((int) 3.5)
evaluates to 3
rather than to 3.5
, because the conversion to type int
discarded the fractional part of the value. That's analogous to this C++ code:
static_cast<double>(static_cast<int>(3.5))