aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes casting 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" Watch "casting" New topic
Author

casting

Mugdha Deo
Greenhorn

Joined: Nov 30, 2000
Posts: 13

This is a question from marcus greens's exam # 1. Q17
I thought the answert would be 1, but the answer is 3.
Can some one please explain?
Thanks,
Mugdha.

What will happen if you attempt to compile and run the following code?
1) Compile and run without error
2) Compile time Exception
3) Runtime Exception

class Base {}
class Sub extends Base {}
class Sub2 extends Base {}
public class CEx{
public static void main(String argv[]){
Base b=new Base();
Sub s=(Sub) b;
}
}
Rajiv Ranjan
Ranch Hand

Joined: Sep 28, 2000
Posts: 61
Hi Mugdha,
This is because you are trying to squeeze a super class into a subclass.
Sub s=(Sub) b; // not desirable.
This will work during compilation as but will throw a runtime exception.
Rajiv
Nasir Khan
Ranch Hand

Joined: Nov 04, 2000
Posts: 135
There won't be any error if
class Base {}
class Sub extends Base {}
class Sub2 extends Base {}
public class CEx{
public static void main(String argv[]){
Base b;//no need to initilized
b=new sub();// for avoiding runtime error
Sub s=(Sub) b;

}
}
Mugdha Deo
Greenhorn

Joined: Nov 30, 2000
Posts: 13

So,
Does it mean that upward casting or explicit casting always result in runtime errors?
Thanks,
Mugdha.
Thomas Paul
mister krabs
Ranch Hand

Joined: May 05, 2000
Posts: 13974
You will always get a run time error if you cast an object into something it is not. A Base object is not a Sub object so casting a Base object into a Sub object will generate a run-time error.


Associate Instructor - Hofstra University
Amazon Top 750 reviewer - Blog - Unresolved References - Book Review Blog
Nissi Hari
Greenhorn

Joined: Oct 31, 2000
Posts: 2
Just Remember that casting of references is fine if it goes upwards in the inheritance tree . Suppose u create a sub object(using new), which is the subclass and cast it to a Base object it is fine.Because in this case you are going up the in inheritance hierarchy.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: casting