It's not a secret anymore!
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


rajani peddi
Ranch Hand

Joined: Nov 27, 2000
Posts: 73
class A {
class B extends A {
class C {
public static void main(String args[])
B sub = new B();
A sup = sub;
System.out.println(((A) sub));
The output here is B (ofcourse it also has @ and a memory address due to toString() ).
What surprises me is that when sub is cast to A should it not print A instead. I want to know what is the actual use of object casting. Can anyone explain the effect of casting an object of subclass to a super class?
Thank you
bill bozeman
Ranch Hand

Joined: Jun 30, 2000
Posts: 1070
Java always knows what the obect is. So when you initilize an object, it knows that it is of type B and it doesn't forget that. You can upcast it to A(), but it still knows it is a B(). If there was a subclass of B() called C() and you tried to downcast it to C() then you would get a runitme error becuase it was never a C() to begin with.
So it should print B() because that is what the class is.
I agree. Here's the link:
subject: Casting
jQuery in Action, 3rd edition