Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Upcast versus Downcast

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?

like image 766
user3317186 Avatar asked Feb 17 '14 00:02

user3317186


1 Answers

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.

like image 111
Sotirios Delimanolis Avatar answered Oct 08 '22 12:10

Sotirios Delimanolis