Reputation: 1435
I am having some issues understand something about abstract classes. I have an abstract class created with a method for setting/getting a name:
public abstract class Person {
private String firstName;
public void setFirstname(String name)
{
this.firstName = name;
}
public String getFirstName()
{
return firstname;
}
I have 2 other classes that extend this class and they are Worker
and Employer
. I have the different workers and employers being created and stored into arraylists in a forth class called WorkPlace
. My question is if I wanted to get every first name of every Person
is there a way to do it without going through each arraylist and doing something like workerList.get.getFirstName
?
Upvotes: 0
Views: 166
Reputation: 411
What you could do is override the toString()
method in your Person
class and return the first name.
When you then get out of ArrayList.toString()
is a something like [firstname1, firstname2, firstname3]
. You can remove the leading and trailing brackets and split the string with with ", "
. This is a bit complicated and may decrease performance because of unnecessary string operations, but you would not required to loop over all elements in the collection.
Here is an example:
// in Person class do this
@Override
public String toString() {
return this.firstName;
}
// in your WorkPlace class do this
public String[] getAllFirstNames() {
String allNames = workerList.toString();
allNames = allNames.substring(1, allNames.length - 2);
return allNames.split(", ");
}
This should work and there is no loop (better: no loop you've written by your own). But as mentioned before, it may cost to much. In addition it may be not very save, in case the behavior of the collection's toString()
method changes.
Upvotes: 1
Reputation: 2079
so if you have:
ArrayList<Person> list = new ArrayList<Person>();
Then:
Employer e1 = new Employer();
Worder w1 = new Worker();
list.add(e1);
list.add(w1);
Then you have to do:
list.get(0).getFirstName();
Upvotes: 0
Reputation: 1607
Perhaps you could create a class like Workplace
, and whenever you want a new Employer or Worker you would call something to the effect of workplaceName.newWorker()
, which would return a new Worker
and at the same time keep track of all Worker
s, so that you can later call workplaceName.getAllWorkerNames()
.
Upvotes: 1
Reputation: 5112
Not unless your abstract class statically keeps a record of all first names, and you provide a static method to get all of those names.
Upvotes: 3