You're right, you are missing something pretty basic.

If you have a method that must return type Object or any less specific
class than the class you KNOW it to be, you use an explicit cast when
referring to the returned reference.  The Java runtime will issue a
run-time error if you make an illegal cast.  Here is an example (I didn't
compile this so I apologize for any lazy syntax errors).

class StringArray extends Object
{
   Vector arrayOfStrings;

   StringArray( String [] args )
   {
      int i;
      for ( i = 0; i < args.length; i++ )
         arrayOfStrings.addElement(args[i]);
   }

   String getElement( int i )
   {
      //****  LOOK HERE ***** the next line casts a generic Object to a String
      return (String) arrayOfStrings.elementAt(i);
   }   
};

Douglas Toltzman

At 02:15 AM 10/3/98 -0500, you wrote:
>Hi,
>
>Please pardon the email handle (just something I picked to separate
mailing-lists) and the (possibly, new to the mailing-list) off-topic-ness
of this question...
>
>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?
>
>Thanks,
>
>--Fred McDavid
>

Reply via email to