Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

[object can't cast]????

 
chao-long liao
Ranch Hand
Posts: 78
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Marcus Green mock exam..
class Base {}
class Sub extends Base {}
public class A{
public static void main(String argv[]){
Base b=new Base();
Sub s=(Sub) b;
}
}
compile without error,but with runtime exception...why??
only primitive data can cast??
 
Ashik Uzzaman
Ranch Hand
Posts: 2373
Eclipse IDE Firefox Browser Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Liao,
Try this instead!
code:
class Base {}
class Sub extends Base {}
class A{
public static void main(String argv[]){
Base b=new Base();
//Sub s=(Sub) b;//Line :1 Here is the runtime exception!
Base c= new Sub();
Sub d = (Sub) c;
}
}
What happens is that in compile time the compiler only checks the references have compatibilty or not, as you have casted it properly in line : 1. But in runtime a subclass cannot caontain a superclass object. Here i m a little whether i m right about in runtime what happens.
Someone expalin plz....

------------------
azaman
 
Sunetra Saha
Ranch Hand
Posts: 77
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The code would compile and run if it were changed to
Base b = new Sub(); //As casting to parents are always allowed
Sub s = (Sub) b; //As b is really an instance of the Sub class, there is no casting problem.
In your case the compiler does not omplain as you have used the cast. The complier checks for type of b and is assured that it can contain objects of type Sub. So it passes compilation. However at runtime , the object in b is not of type Sub but of type base - its parent. This sort of casting is not allowed. So the JRE complains.
I hope it is clear, if not please let us know.
 
Ashik Uzzaman
Ranch Hand
Posts: 2373
Eclipse IDE Firefox Browser Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Dear Sunetra, U have cleared all my confusions....
------------------
azaman
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic