I am trying to use a vector to hold my classes. These classes inherit methods from another class and have their own methods as well. What I am having trouble with is using the vector with objects to call the methods from the class within the object. I thought it would be something like:
public static void vSort(Vector<Object> vector) {
vector[0].generate();
}
with generate being a custom method i created with the student class within the object.
A better example
public class Method {
protected String name;
public void method() {
// some code
}
}
public class Student extends Method {
protected String last;
public void setUp() {
// some code
}
}
public class Main {
public static void main(String[] args)
{
Vector<Object> vector = new Vector<Object>();
Student stu = new Student(); // pretend this generates something
vector.add(stu);
}
The problem i am running into is there are many classes like student that build on Method. If i cant use Object that is fine with me but i need to access the code within the Method class.
Vector
is synchronized - Jeffrey 2012-04-05 23:05
Java doesn't have operator overloads. So the syntax is:
vector.get(0).generate();
However, this won't work at all in your case, because you have a Vector<Object>
, and an Object
doesn't have a generate
method.
[Tangential note: vector
is de facto deprecated; you should probably use ArrayList
instead.]
you should use vector.get(0)
to retrieve your object.
Also note, that Object
does not declare generate()
- so you are going to need to cast or specify your object as the generic type.
When you have a Vector<Object>
, all the retrieval methods return Object
, so you can't call subclass methods unless you explicitly downcast. You should use Vector<YourClass>
instead, so that the references you get out of the vector are of type YourClass
and you don't have to downcast them.