This week's book giveaway is in the Jobs Discussion forum.
We're giving away four copies of Java Interview Guide and have Anthony DePalma on-line!
See this thread for details.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes cast question 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 "cast question" Watch "cast question" New topic

cast question

Simeon Shi
Ranch Hand

Joined: Dec 09, 2001
Posts: 35
why the following code will generate an runtime exception?
public class CastTest{
public static void main(String[] args){
Base b = new Base();
Sub s = (Sub)b;
class Base{}
class Sub extends Base{}
actually,Sub is subclass of class Base.why?
3x in advance
Rob Ross

Joined: Jan 07, 2002
Posts: 2205
At runtime, when this line is executed:
Base b = new Base(); //line 1
The variable b contains a reference to an instance of type Base.
In the next line, you try to assign that instance to a variable of type Sub.
Sub s = (Sub)b; //line 2
However, the instance in b is NOT an instance of Sub, so the runtime system complains.
If in line 1 above you had instead written
Base b = new Sub();
then line 2 would not throw an exception , because when you cast b to a Sub, it is the correct type.

SCJP 1.4
Arsho, Ayan
Ranch Hand

Joined: Nov 14, 2001
Posts: 60
But if you declare it like this it will NOT throw out an runtime exception
Base b = new Sub();
[ January 14, 2002: Message edited by: Arsho, Ayan ]
Ragu Sivaraman
Ranch Hand

Joined: Jul 20, 2001
Posts: 464
casting down gives a runtime exception.. class cast to be exact
Jose Botella
Ranch Hand

Joined: Jul 03, 2001
Posts: 2120
I can't help saying that if this were allowed, the instance of type Base could receive messages for which it is not prepared to response. They are the methods that were added in Sub but they don't exist in Base.

SCJP2. Please Indent your code using UBB Code
Axel Janssen
Ranch Hand

Joined: Jan 08, 2001
Posts: 2164
This is another just-another-informal-explanation:
For me it was easiest to remember if you think about is-a-relationship.
Objects of class Sub is-a Base?
Thats true!!!
Objects of class Base is-a Sub?
Thats NOT true!!!
Class Sub is more than a Base. Its an extended Base. So you cant assign a class Sub reference variable to a class Base object.
The other case is valid:
You can assign a class Sub Object to a class Base reference variable, because a Sub-Object is-a (extended) Base object.

I agree. Here's the link:
subject: cast question
It's not a secret anymore!