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

Casting question

Anonymous
Ranch Hand

Joined: Nov 22, 2008
Posts: 18944
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

Joined: Mar 17, 2000
Posts: 5782
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).]


Open Group Certified Distinguished IT Architect. Open Group Certified Master IT Architect. Sun Certified Architect (SCEA).
Anonymous
Ranch Hand

Joined: Nov 22, 2008
Posts: 18944

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
 
 
subject: Casting question
 
Similar Threads
Will class casting creats new object on the heap?
some Java concepts
Confused help me!!
java programmer certificate
Another mock exam question.