ArrayList无法识别子类变量

问题描述:

我在查看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中,并且一切都完美无缺。

任何帮助将不胜感激!

+0

您确定您的人员列表只包含客户端实例吗?如果没有,你会得到错误。我也没有看到你的发布代码是如何编译的,除非你在尝试'x.clientID'之前将'x'强制转换为'Client'类似于'((Client)x).clientID == cid' –

你必须要么把它们放在一个单独的列表或丢掉。

for (Person person : people) { 
    if (person instanceof Client) { 
    Client client = (Client) person; 
    if (client.clientID == cid) { 
     System.out.println("found!"); 
    } 
    } 
} 
+1

非常感谢!我不知道我是如何忘记的。大约在两周前详细解释了这一点。 –

您正在使用私有实例变量。在他们自己的班级以外的任何地方都不可见。 更改为受保护或公共安全。变量,并应该解决这个问题。

而且这个代码

x.clientID == cid 

正在寻找实例变量在Person抽象类,并且因为没有这样的变量,你让编译器错误。

问候!

+0

很抱歉,这些实际上意味着被列为受保护的,忽略了当我输入问题时。编辑的OP也是如此。 –

+0

你也不用担心inst。变量是你班级的一部分。 X.clientID不会工作,因为Person类没有cliendID不是它的一部分。 – Mechkov

你需要转换PersonClient

((Client) x).clientId; 

的一点是,ClientID属性没有按” t属于父类Person。使用这种方法实例来降低对象:

for(Person x : people) { 
    if (x instanceof Client){ 
     Client c = (Client) x; 
     if(c.clientID == cid) { 
      System.out.println(x); 
     } 
} 

即使这是可能的,它通常是一个信号,你有一个设计问题。可能需要重构代码,例如将Person的不同子类存储到不同的ArrayList中。