Two Laptop Bag*
The moose likes Mock Exam Errata and the fly likes Casting Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Certification » Mock Exam Errata
Bookmark "Casting" Watch "Casting" New topic
Author

Casting

neelam samnani
Greenhorn

Joined: Mar 12, 2001
Posts: 8
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.


Neelam
Lokesh Mahajan
Greenhorn

Joined: Feb 01, 2001
Posts: 22
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

Joined: Jan 09, 2001
Posts: 1492
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

Joined: Mar 14, 2001
Posts: 13
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.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Casting
 
Similar Threads
About casting
downcasting
Constructor initialization
cast question
Question on Marcus Green's Exam 1