Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Casting question

 
Anonymous
Ranch Hand
Posts: 18944
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
class Base
{
void test() {
System.out.println("Base.test()");
}

}
////////////////////////////////////////////
public class Child extends Base {

void test() {
System.out.println("Child.test()");
}

static public void main(String[] a) {
Child anObj = (Child)new Base();
anObj.test();
}
}
In this case , why am i getting a ClassCastException.
here Child inherits from Base and I am casting base to a child. explicitly down casting.
I couldn't figure this one out.
Could someone please explain it to me.
Thanks in advance to all of those who reply to this note.
 
Ajith Kallambella
Sheriff
Posts: 5782
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Smithani,
Explicit downcastings are usually potential candidates for ClassCastException. This occurs when rutime type of the objects cannot be cast to the type being cast to.
What you are doing here is assigning an object of Base type to the Child class. When you say new Base(), it creates a Base object. When you assign it to a child reference with an explicit cast , it violates the runtime rules becase Child is more "specialized" than Base is and this assignment simply doesn't make sense. The compiler checks to see if the object being assigned is of the same type as the object being assigned to, or of a subclass type. When you do an explicit cast, you are telling the compiler not to worry, and you will make sure they are compatible _at runtime_. That's why it compiles, but blows up at runtime.
There is a set of rules that you should remember for reference assignment and casting. Though the rules looks complicated, most of it is common sense. I can tell you this, looking at mock exams, you can expect this kind of questions and so be 100% sure with these concepts.
If I can be of any more help, let me know.
Ajith

[This message has been edited by Ajith Kallambella (edited May 26, 2000).]
 
Anonymous
Ranch Hand
Posts: 18944
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Additional info at this link:
Similar discussion
If you need more details, try search with the "class cast exception". Not too many about 10-12 I got.
Regds.
- satya
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic