Win a copy of Learn Spring Security (video course) this week in the Spring forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

cast question

 
Simeon Shi
Ranch Hand
Posts: 35
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Bartender
Posts: 2205
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
Rob
 
Arsho, Ayan
Ranch Hand
Posts: 60
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
But if you declare it like this it will NOT throw out an runtime exception
Base b = new Sub();
-Thanks
[ January 14, 2002: Message edited by: Arsho, Ayan ]
 
Ragu Sivaraman
Ranch Hand
Posts: 464
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
casting down gives a runtime exception.. class cast to be exact
Ragu
 
Jose Botella
Ranch Hand
Posts: 2120
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Axel Janssen
Ranch Hand
Posts: 2166
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.

Axel
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic