aspose file tools*
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
Author

I was expecting ClassCastException ?

Mahtab Alam
Ranch Hand

Joined: Mar 28, 2012
Posts: 300

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
K. Tsang
Bartender

Joined: Sep 13, 2007
Posts: 2596
    
    9

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/OCM-JD OCPJP7 OCPWCD5 OCPBCD5
Matthew Brown
Bartender

Joined: Apr 06, 2010
Posts: 4464
    
    8

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
Greenhorn

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

 
It is sorta covered in the JavaRanch Style Guide.
 
subject: I was expecting ClassCastException ?