jQuery in Action, 2nd edition*
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


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
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: 222

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

Joined: Sep 13, 2007
Posts: 2229
    
    7

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
Matthew Brown
Bartender

Joined: Apr 06, 2010
Posts: 4338
    
    7

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

 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: I was expecting ClassCastException ?
 
Similar Threads
Inteface Sub Class
casting
ClassCastException
ClassCastException in Generic code
what this line meens...