我在查看ArrayList中的子類屬性時遇到了問題。ArrayList無法識別子類變量
下面是我的代碼的重要部分的一些片斷,這裏很重要。
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;
}
當使用一個for循環clientID的搜索,我得到
Enterprise.java:134:找不到符號 符號:變量clientID的 位置:Person類
我曾嘗試帶和不帶instanceof Client的for循環。我也嘗試在for循環參數中使用Client而不是Person。
for(Person x : people) {
if(x.clientID == cid) {
System.out.println(x);
}
在將它們轉換爲子類之前,我把它們放入了它們自己類型的ArrayList中,並且一切都完美無缺。
任何幫助將不勝感激!
您確定您的人員列表只包含客戶端實例嗎?如果沒有,你會得到錯誤。我也沒有看到你的發佈代碼是如何編譯的,除非你在嘗試'x.clientID'之前將'x'強制轉換爲'Client'類似於'((Client)x).clientID == cid' –