Java downcast question

C

Chad

Given the following code...

class X {}
class Y extends X {}
class Z extends X {}

public class Main {

public static void main(String[] args) {
X x = new X();
Y y = new Y();
Z z = new Z();

Y o6 = (Y) x; //<--error
}

}

I get...

run:
Exception in thread "main" java.lang.ClassCastException: X cannot be
cast to Y
at Main.main(Main.java:12)
Java Result: 1
BUILD SUCCESSFUL (total time: 0 seconds)

Why can't I downcast X to Y? Y inherits X.

Chad
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,061
Latest member
KetonaraKeto

Latest Threads

Top