Hey yall, I'm trying to typecast an object from a class and I get the following error when I try to run it: java.lang.ClassCastException at funnelexppkg.funnel.tryMove(funnel.java:90) the code in question is:
while this looks like a valid cast, it will not compile. Any ideas? Thanks in advance Gabe
As you can see on line 89, you define temp to be an Object: Object temp = new Object(); However, on line 90, you attempt to cast it to a "marble". That of course freaks out, since it is an Object -- not a marble.
Well, that works, but now I am getting an underFlowException on this line:
Anything? [ March 17, 2004: Message edited by: Gabriel White ]
Joined: Mar 02, 2003
still need some help.... I really don't see why I can't perform a statement like this one: ((marble)temp).setTime(time); This is a valid class cast but I still get a hang up on it. as you can see temp is an object but I need to cast it as a marble object, as the method requires me to return a marble object. I just am having problems doing this. ...I figured out the UnderflowExceptions any help is appreciated. Thanks Gabe
You cannot change the type of an object. In Java, casting is more a mechanism of using a reference of some type, to get a reference of a different type that points to the same object. When you created your temp object, the object (and the reference) were of type Object. An Object is not a marble (though a marble is an Object), so you cannot have a reference of type marble that points to an object that is only of type Object. The marble type reference would only be good for pointing to objects of type marble (or one of its subtypes). Take a look at a few of the JavaRanch Campfire Stories, especially the "How my Dog learned Polymorphism" story. The "Cup Size" and "Pass-by-Value Please" stories are good reads as well. Are things making a bit more sense now?
Im just saying that there is nothting wrong with this: Marble is a class. I have casted a temp object as a marble object. However my compiler will not let me get by it. It keeps giving me a classcast exception.