Reputation: 23
I am having a problem with seeing subclass attributes in an ArrayList.
Here's some snippets of the main parts of my code that matter here.
private ArrayList<Person> people = new ArrayList<Person>;
abstract class Person {
String fName;
String lName;
}
public class Employee extends Person {
protected int empID;
}
public class Client extends Person {
protected int clientID;
}
When using a for loop to search by clientID, I am getting
Enterprise.java:134: cannot find symbol symbol : variable clientID location: class Person
I have tried with and without instanceof Client on the for loop. I have also tried using Client instead of Person in the for loop parameters.
for(Person x : people) {
if(x.clientID == cid) {
System.out.println(x);
}
Before turning these into subclasses I had them in an ArrayList of their own kind and everything worked flawlessly.
Any help would be greatly appreciated!
Upvotes: 2
Views: 688
Reputation: 39164
The point is that clientID property doesn't belong to parent class Person. Use instanceof this way in order to downcast the object:
for(Person x : people) {
if (x instanceof Client){
Client c = (Client) x;
if(c.clientID == cid) {
System.out.println(x);
}
}
Even if that is possible, it is often a signal that you have a design problem. Probably you need to refactor your code, for example storing different subclass of Person into different ArrayList.
Upvotes: 0
Reputation: 45568
You have to either put them in a seperate list or cast them:
for (Person person : people) {
if (person instanceof Client) {
Client client = (Client) person;
if (client.clientID == cid) {
System.out.println("found!");
}
}
}
Upvotes: 4
Reputation: 4324
You are using Private instance variables. There are NOT visible anywhere outside their own class. Change to protected or public inst. variables and should fix the issue.
Also this code
x.clientID == cid
is looking for instance variable in the Person abstract class, and since there is no such variable you get the compiler error.
Regards!
Upvotes: 0