On Sat, 3 Oct 1998 02:15:03 -0500 (EST), Fred McDavid wrote:

>Hi,
>
>I keep hitting an obstacle while coding and I was hoping someone here
>could help enlighten me:
>
>A bunch of the java-standard methods return "Object" and when I try to
>use them, I get the following error:
>
>  >> Incompatible type for declaration. Explicit cast needed to convert
>     java.lang.Object to (whatever)
>
>In this particular instance, I've created a class which is a descendant
>of java.awt.Checkbox.  I add an ItemListener and the listener, therefore,
>receives an ItemEvent.  I call ItemEvent::getItem() and try to call a
>method that I've created for the descendant class...hence the error which
>would seem to imply that if I'm going to use the ItemEvent (or the java
>hashtable or a bunch of other stuff that I've just worked around), I
>can only call Object::(whatever Object methods there are) after my
>objects go thru the mill.
>
>I'm pretty sure whatever I'm missing is pretty basic...could anyone
>shed some light on this for me?

Well, are you asking why or how?

The "why" a generic "Object" type is returned from a number of methods
is because these methods are usually dealing in the abstract with any
type of object - such as the java.util.Vector class is able to store any
object type.  Since all objects are subclasses of Object, the methods
are defined to take (and return) an Object so that you are now able to
use an object of any class, including those of your making.

The "how" to get arround this is much like C/C++ type casting.  If,
for example, you have stored objects of class java.lang.String in a
vector, you would get them back out as follows:

        java.util.Vector myVector=new java.util.Vector();

        myVector.addElement("A string as an element");

        String data;

        data=(String) myVector.elementAt(0);

Now, note that even though a bit of code like this in C could be
dangerous since you could be taking some other object and saying
it was a String, in Java, at run time (since the compiler can not
know what type of object is in the vector) the JVM will make sure
that the object returned is a String object otherwise an exception
will be raised.

If you have an object you can also find out what its type is or
you can ask if it is an instance of a specific class without the
overhead of a try/catch of an exception while trying to typecast
the object.  In most cases one actually knows that all the elements
in a vector are strings/etc so normally the cast is all that is
needed or wanted.

Michael Sinz -- Director of Research & Development, NextBus Inc.
mailto:[EMAIL PROTECTED] --------- http://www.nextbus.com
My place on the web ---> http://www.users.fast.net/~michael_sinz

Reply via email to