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 Class Cast Exception Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Java Interview Guide this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Class Cast Exception" Watch "Class Cast Exception" New topic

Class Cast Exception

rajiv kothari

Joined: Sep 23, 2006
Posts: 1
Hi.....I am confused about this question. The below code throws a ClassCast Exception at runtime. Can someone please explain why its doing that?
Thanks in advance

class A {

public class B extends A

public static void main(String[] args) throws Exception
B b = new B();
Object ob = new Object();
b = (B)ob;

Keith Lynn
Ranch Hand

Joined: Feb 07, 2005
Posts: 2398
You cannot cast the reference to an object which is an instance of Object to a subclass type. In general, you cannot cast a reference to an object whose runtime type is a superclass to a subclass reference.

Note that the cast is allowed at compile-time because there are situations in which you can cast a superclass reference to a subclass reference.

In this case, you can call a B object an Object, but you cannot call an Object a B.
[ September 23, 2006: Message edited by: Keith Lynn ]
Paul Anilprem
Enthuware Software Support
Ranch Hand

Joined: Sep 23, 2000
Posts: 3635
You need to understand two things here:
1. At compile time, the compiler checks whether the cast you are trying to do is at all possible in any situation. If no, then there is a compiler error. e.g.
class A{} class B{}
A a = new A();
B b = (B) a; // a can NEVER point to an object of class B. So this is a compilation error.
Object o = b;
a = (A) o; //This is valid because the reference o CAN (whether it actually does or not is not checked at compile time) point to an object of class A at runtime because A is a subclass of Object and thus A IS-A Object.

2. At runtime, the JVM checks whether or not the object referred to by the reference that you are trying to cast, actually points to an object of the class given on the left hand side of the assignment. If not, then a ClassCastException is thrown.
By throwing this exception, the JVM is trying to tell you that the given object is not really of the class that you think it is.

So, at runtime, A a = (A) o; will throw the exception because o is actually pointing to an object of class B and B IS-NOT-A A.

OK, Quiz time :
class A{}
class AA extends A{}
Object o = new AA();
A a = (A)o; // what will happen here? Will it compile, will it run?

Enthuware - Best Mock Exams and Questions for Oracle Java Certifications
Quality Guaranteed - Pass or Full Refund!
I agree. Here's the link:
subject: Class Cast Exception
It's not a secret anymore!