File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Casting ......confusion 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 "Casting ......confusion" Watch "Casting ......confusion" New topic
Author

Casting ......confusion

Mukti Bajaj
Ranch Hand

Joined: Dec 11, 2000
Posts: 59
Hi,
Why does this code....compiles and runs fine.
class Base {}
class Sub extends Base {}
public class CEx{
public static void main(String argv[]){
Base b=new Base();
Sub s=new Sub();
b =s;
s=(Sub)b;
}}
But, at the same time this code produces Runtime ....ClassCastexception
class Base {}
class Sub extends Base {}
public class CEx{
public static void main(String argv[]){
Base b=new Base();
Sub s=new Sub();
s=(Sub)b;
b =s;
}}
can someone please explain.
Thanks,
Mukti
Zheng Huang
Ranch Hand

Joined: Dec 20, 2000
Posts: 49
In your 1st code b points to a class Sub object. In your 2nd code b does not points to a class Sub object. Down casting is not allowed.
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: Casting ......confusion