Reputation: 115
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?
Upvotes: 11
Views: 5331
Reputation: 94469
When an instance of type Y
or Z
(subclass) is treated as the base type (superclass) X
this is an upcast.
Upcasts are implicit(hidden) and cause a derived type to be treated as a super type.
This is an example of an upcast:
X x1 = y;
The cast is implicit (hidden) but could be thought of as:
X x1 = (X) y;
A downcast is from a super type to a derived type. So to downcast x1
to the type Y
:
X x1 = y;
Y y1 = (Y) x1;
Downcasts are not implicit and must be explicitly declared. They create the potential for a ClassCastException
if the instance we are casting is not of the type we are casting to.
Upvotes: 3
Reputation: 1980
It is upcasting, because you have an instance of type Y which is referenced by a variable of type X, and X is ´up´ (above) in the class hierarchy.
Upvotes: 0
Reputation: 279990
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
.
Upvotes: 8
Reputation: 2453
Y extends X means that the objects you create with new Y()
will be of type Y and consequently of type X. Because one derives from the other and X is the super class, any object that is of type Y is also of type X.
For example all classes in java derive from the Object class, hence, a String is a string and also an Object.
Upvotes: 0