I have the following code
class X{}
class Y extends X{}
class Z extends X{}
public class RunTimeCastDemo{
public static void main(String args[]){
X x = new X();
Y y = new Y();
Z z = new Z();
X x1 = y; // compiles ok (y is subclass of X), upcast
X x2 = z; // compiles ok (z is subclass of X), upcast
The code above was given to me in a lecture. I know that X is the base class of both Y and Z. x is a reference to an X type object, y is a reference to an Y type object, and z is a reference to a Z type object. The part that is confusing me is the last two lines of the code. From my understanding, the reference x1 of type X is assigned the same reference as y which is type Y. Since x1 is assigned to the same reference as y, that means it goes from type X to Y which would be downcasting. Am I reading the code wrong?
Your class hierarchy
Object
|
X
/ \
Y Z
From my understanding, the reference x1 of type X is assigned the same reference as y which is type Y. Since x1 is assigned to the same reference as y, that means it goes from type X to Y which would be downcasting. Am I reading the code wrong?
X x1 = y; // compiles ok (y is subclass of X), upcast
You're assigning y
to x1
. You're assigning a reference of type Y
to a reference of type X
. Looking at the hierarchy, you're going upwards, thus upcast
.
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