• Post Reply Bookmark Topic Watch Topic
  • New Topic

upcasting problems!! help!  RSS feed

 
Ren Shao
Ranch Hand
Posts: 51
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
this code can be compiled properly
**************************************
class Parents {}
class Children extends Parents{
Children child(){
return (Children)new Parents();
}
}
**************************************
but how come this one can't ??
**************************************

class Children{
Children child(){
return (Children)new Object();
}
}
**************************************
the text book says all class inherited from
Object automatically. why this one can't be compiled properly?

[ December 23, 2002: Message edited by: Ren Shao ]
 
John Lee
Ranch Hand
Posts: 2545
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
To convert a class to another class,
OldClass B = New OldClass() ;
NewClass A = (NewClass) B ;
OldClass has to be a subclass of NewClass, so this statement is wrong:
return (Children)new Object();
Apparently, Object is superclass of everyone.
 
Dirk Schreckmann
Sheriff
Posts: 7023
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Welcome to JavaRanch, Ren!
why this one can't be compiled properly?
Both examples will compile just fine. Both examples will also create the same runtime exception (ClassCastException) as they both try to create a reference of type Children to an object that is not of type Children.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!