• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Casting

 
rajani peddi
Ranch Hand
Posts: 73
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
rajani
 
bill bozeman
Ranch Hand
Posts: 1070
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
Bill
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic