File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes I was expecting ClassCastException ? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "I was expecting ClassCastException ?" Watch "I was expecting ClassCastException ?" New topic

I was expecting ClassCastException ?

Mahtab Alam
Ranch Hand

Joined: Mar 28, 2012
Posts: 388

Why this does not result in ClassCastException

class A{}
class B extends A{}
class C extends B{}
class Test1
public static void main(String args[])
A a=new C();
A a1=(B)a;

a is referencing to a C Object , trying to cast in B should have result in exception

Oracle Java Programmer , Oracle SQL Expert , Oracle Java Web Component Developer, Oracle Web Service Developer
K. Tsang

Joined: Sep 13, 2007
Posts: 3132

Ok your class setup says C is a B and B is a A, which makes C is a A.

The main says variable a is a C (which we know is a B). Then variable a1 cast this to a B (variable a's parent class B which is a A).

You should try down-casting... then ClassClassException should throw. I let you figure out the code to test that.

K. Tsang JavaRanch SCJP5 SCJD OCPJP7 OCPWCD5 OCPBCD5 OCPWSD5 OCMJEA5 part 1 part 2/3
Matthew Brown

Joined: Apr 06, 2010
Posts: 4543

Mahtab Alam wrote:a is referencing to a C Object , trying to cast in B should have result in exception

A C IS-A B (because C extends B), so the cast is fine.
indi man

Joined: Mar 12, 2013
Posts: 1
Instead this will give ClassCastException
A a=new C();
B b=(B)a;
C c=(A)b

I agree. Here's the link:
subject: I was expecting ClassCastException ?
It's not a secret anymore!