This week's book giveaway is in the Mac OS forum.
We're giving away four copies of a choice of "Take Control of Upgrading to Yosemite" or "Take Control of Automating Your Mac" and have Joe Kissell on-line!
See this thread for details.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes object casting Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "object casting" Watch "object casting" New topic
Author

object casting

Saman Perera
Ranch Hand

Joined: Jul 15, 2003
Posts: 61
hi all
class Base{}
hi all
class Sub extends Base{}
class Sub2 extends Base{}
public class CEx{
public static void main(String ar[]){
Base b = new Base();
Sub s = (Sub)b;// run time error in this line
}
}
pls explain why there is a runtime error?
thank you
saman
Jose Botella
Ranch Hand

Joined: Jul 03, 2001
Posts: 2120
(Sub) b
this makes the compiler happy because the compile type of "b" (Base) is a supertype of Sub. However because it is a downcast the "interpreter" must make another check at runtime. It must ensure that the object pointed by "b" is really an object of type "Sub" (or one of its subtypes)
If the last check were not carried out, an object of type Base could be referred by a variable of type Sub; this could lead to such object to receive a method call declared in type Sub but not in Base. That is an object could receive a message for which is not prepared for. Java is a type safe language. You cannot call methods on objects that do not correspond with its type.
The exact rules for casting are given in JLS 5.5 Casting Conversion
As a general guide, keep in mind that the compiler will complain if there is no hierarquical relationship between the compile type of the expression to be casted "b", and the type inside the cast operator "()" (*). Later at runtime, a check of the real type of the object pointed by the expression maybe needed.
(*) Say there there is no a father-son relationship but they are siblings.


SCJP2. Please Indent your code using UBB Code
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: object casting