jQuery in Action, 2nd edition
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes casting Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Reply Bookmark "casting" Watch "casting" New topic
Author

casting

vini singh
Greenhorn

Joined: Dec 04, 2008
Posts: 18
class A{}
class B extends A{}
class C extends A{}

final class D extends B{
public void doMethod(){
A a=new B();
B b=new D();
C c=new C();
D d=null;
//Insert Here
}
}


d=(D)(B)a //how can thisline cause classcastexception
Ruben Soto
Ranch Hand

Joined: Dec 16, 2008
Posts: 1032
It will compile fine, but it will issue a ClassCastException, because a refers to a B object, and B is not a D (it is the other way around.)

The first cast is OK, it is the second cast that is the problem:
(D)(B)a


All code in my posts, unless a source is explicitly mentioned, is my own.
Jor Cheung
Greenhorn

Joined: Jan 08, 2009
Posts: 1
(B)a is valid since a is an object of class B. However (D)(B)a is not valid since you can not cast an object B to class D as you can not "cast down".

Yuan Du
Ranch Hand

Joined: Nov 20, 2008
Posts: 34
Hi,

It will alway throw ClassCastException if i try to down cast a object.

But why trying to down cast a null object, it doesn't throw NullPointException in Runtime.

eg.
Object o = null;
Integer i = (Integer)o;

Could you please explain it?

Thanks,

Yuan
Ruben Soto
Ranch Hand

Joined: Dec 16, 2008
Posts: 1032
Hi Yuan,

The null literal is a special literal of the null type, which denotes that the reference it is assigned to doesn't point to any object.
A reference of any type can be assigned null, and that is why downcasting is working in that sense. Normally, for downcasting you need to consider the actual type of the object involved. But for a null reference there is no object pointed to, so you can cast a null reference to any type.
Yuan Du
Ranch Hand

Joined: Nov 20, 2008
Posts: 34
Thank you Ruben!

Yuan
Ruben Soto
Ranch Hand

Joined: Dec 16, 2008
Posts: 1032
No problemo! Just remember that you don't cast objects, but references. Upcasting always works, but for downcasting you have to make sure that the actual object's type satisfies the Is-A relationship for the type you are attempting to downcast the reference pointing to that object to.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: casting
 
Similar Threads
Another examLab casting question
casting
Final Class cannot be instantiated
Explanation for the statements
class casting