Link to home
Start Free TrialLog in
Avatar of Sapphireblue
SapphireblueFlag for United States of America

asked on

calling a method of an object stored in a vector

This works fine:

      RosterStudent2 currentStudent = new RosterStudent2();
      currentStudent = (RosterStudent2) studentsVector.get(studentIndex);

But this gives me the error "cannot resolve symbol symbol  : method getName  () location: class java.lang.Object":


How can I call getName() on a RosterStudent2 object inside the studentsVector vector using the index value of the vector? Thanks!
Avatar of baboo_

Link to home
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of udo_borkowski

Normally the code you wrote should work fine if you are using a "Vector" class and only added RosterStudent2 objects to the vector.

Can you post the code that actually creates the vector and adds the students?

(A problem similar to the one you mentioned can happen when one is using the "toArray" methods and does not provide the proper array as a parameter. Are you using the toArray methods?)
Apparently, your studentsVector.get method returns an object.   While the actual object instance "knows" what type it is at runtime, Java doesn't.  When you call:


it returns (I guess) an Object type reference.  In this line of your working code:

            currentStudent = (RosterStudent2) studentsVector.get(studentIndex);

you cast the returned object to the RosterStudent2 type.  You have to do it in the line that doesn't work, too.  Here's a breakdown of the syntax:

              (RosterStudent2) studentsVector.get(studentIndex)

You need to cast the object returned from studentsVector.get.  Take the above, put it in parentheses, and then call the getName method on it.  (just put the dot after the close paren.)

               ( (RosterStudent2) studentsVector.get(studentIndex) ).getName()

Then, you can use THIS expression as the argument for the nameField.setText method, like this:

                nameField.setText(  ( (RosterStudent2) studentsVector.get(studentIndex) ).getName() );

Avatar of CEHJ
You don't need to create an instance like this

>>RosterStudent2 currentStudent = new RosterStudent2();

It should be

RosterStudent2 currentStudent = (RosterStudent2) studentsVector.get(studentIndex);

and RosterStudent2 must have a getName method
geez....  That first line should read:

"Apparently your studentsVector.get method returns an Object-type object.  While the actual object instance "knows" what type it is at runtime (its type is RosterStudent2), Java doesn't, which is why you need to cast it."
Avatar of Sapphireblue


thanks all. clock's ticking on my last homework of the semester so I'm running with baboo's nice easy answer... but thanks udo and CEHJ, I'm sure I'll be reviewing your comments again come next semester!