aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes [object can't cast]???? 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 "[object can Watch "[object can New topic
Author

[object can't cast]????

chao-long liao
Ranch Hand

Joined: Jul 29, 2001
Posts: 78
Marcus Green mock exam..
class Base {}
class Sub extends Base {}
public class A{
public static void main(String argv[]){
Base b=new Base();
Sub s=(Sub) b;
}
}
compile without error,but with runtime exception...why??
only primitive data can cast??
Ashik Uzzaman
Ranch Hand

Joined: Jul 05, 2001
Posts: 2370

Hi Liao,
Try this instead!
code:
class Base {}
class Sub extends Base {}
class A{
public static void main(String argv[]){
Base b=new Base();
//Sub s=(Sub) b;//Line :1 Here is the runtime exception!
Base c= new Sub();
Sub d = (Sub) c;
}
}
What happens is that in compile time the compiler only checks the references have compatibilty or not, as you have casted it properly in line : 1. But in runtime a subclass cannot caontain a superclass object. Here i m a little whether i m right about in runtime what happens.
Someone expalin plz....

------------------
azaman


Ashik Uzzaman
Senior Member of Technical Staff, Salesforce.com, San Francisco, CA, USA.
Sunetra Saha
Ranch Hand

Joined: Feb 25, 2001
Posts: 77
The code would compile and run if it were changed to
Base b = new Sub(); //As casting to parents are always allowed
Sub s = (Sub) b; //As b is really an instance of the Sub class, there is no casting problem.
In your case the compiler does not omplain as you have used the cast. The complier checks for type of b and is assured that it can contain objects of type Sub. So it passes compilation. However at runtime , the object in b is not of type Sub but of type base - its parent. This sort of casting is not allowed. So the JRE complains.
I hope it is clear, if not please let us know.
Ashik Uzzaman
Ranch Hand

Joined: Jul 05, 2001
Posts: 2370

Dear Sunetra, U have cleared all my confusions....
------------------
azaman
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: [object can't cast]????