File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Casting

 
neelam samnani
Greenhorn
Posts: 8
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Is this program will suceesfully compile and run? If it so then tell me why? & If not so then also tell me why?
According to me it should sucessfully complie and run . But it is showing error(java.lang.ClassCastException)during runtime.
Why it is so? While we are defining it cast .
class Base {}
class Sub extends Base {}
class Sub2 extends Base {}
public class CEx{
public static void main(String argv[]){
Base b=new Base();
Sub s=(Sub) b;
}
}
Pls.help me.
 
Lokesh Mahajan
Greenhorn
Posts: 22
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello Dear
class Base {}
class Sub extends Base {}
class Sub2 extends Base {}
public class CEx{
public static void main(String argv[]){
Base b=new Base();
Sub s = new Sub();
b = s;
s=(Sub) b;
}
}
Try to run this program, it will run now.
Lokesh
[This message has been edited by Lokesh Mahajan (edited March 22, 2001).]
 
Manfred Leonhardt
Ranch Hand
Posts: 1492
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Neelam,
The problem is that you can't just cast anything to anything in Java. In your example you are creating a new Base() class named b. Then you are telling the JVM to convert it to a Sub class. The Base class does not have enough information (missing state!) to perform the conversion. Since Sub extends Base the JVM assumes that there is more state even if you don't actually provide any.
The above code provided by Lokesh "Hello Dear" Mahajan works because b is used to reference the casted type. The statement:
b = s
allows the JVM to perform the casting without any problems because b reference now has all the information it needs for the cast.
Regards,
Manfred.
 
Sarang Gurao
Greenhorn
Posts: 13
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello
the casting rule does not give the compiler error but always give runtime error.
refer to RHE(Roberts , Heller and Ernest) 16 rules for casting in chapter conversion and casting.
 
Don't get me started about those stupid light bulbs.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic