• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Casting ......confusion

 
Mukti Bajaj
Ranch Hand
Posts: 59
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
Why does this code....compiles and runs fine.
class Base {}
class Sub extends Base {}
public class CEx{
public static void main(String argv[]){
Base b=new Base();
Sub s=new Sub();
b =s;
s=(Sub)b;
}}
But, at the same time this code produces Runtime ....ClassCastexception
class Base {}
class Sub extends Base {}
public class CEx{
public static void main(String argv[]){
Base b=new Base();
Sub s=new Sub();
s=(Sub)b;
b =s;
}}
can someone please explain.
Thanks,
Mukti
 
Zheng Huang
Ranch Hand
Posts: 49
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In your 1st code b points to a class Sub object. In your 2nd code b does not points to a class Sub object. Down casting is not allowed.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic