【问题标题】:Inheritance Issues with instanceOf not recognised in IF condition在 IF 条件下无法识别 instanceOf 的继承问题
【发布时间】:2014-01-23 01:15:42
【问题描述】:

我有以下继承层次结构:Staff (Abstract)、HomeWorker (Abstract)、Typist。 Typist 继承自两个抽象类。

我正在实现一个名为 Manager 的接口(用于学术作业)。我在其中实现 Manager 的类称为 Branch。我需要在 Branch 中实现的方法之一是 setEmail,如下所示。

问题是只有打字员有电子邮件地址,其他员工(翻译和文员)没有。所有人员都存储在 TreeMap 中。在尝试调用 setEmail 方法(因为此方法仅存在于 Typist 上)之前,我正在尝试检查 id 参数指定的工作人员是否是 instanceOf Typist。

但是,使用 BlueJ,只要我在 IF 条件中键入 instanceOf,范围突出显示就会告诉我它超出范围,并且在 StaffMember 引用之后需要“)”。

有什么想法吗??

/** Sets email for a typist

 * @param id represents the staff id
 * @param email is the email address
 */ 
public void setEmail(String id, String email)
{
    //Should be done in the typist class. This increases coupling though. 
    //Need to see if there is a way that I can do this using the staff class instead 
    Staff staffMember = staff.get (id);
    //TO DO: Need to put an IF statement in that confirms the staff member is a typist,    otherwise I could end up
    //trying to set an email against a staff type which doesn't store email addresses
    if (staffMember instanceOf Typist)
    {
    staffMember.setEmail(email);      
    }

}

【问题讨论】:

  • Typist inherits from both abstract classes. java 不可能。
  • 关键字是instanceof,而不是instanceOf
  • 抱歉,它在两个类下面的层次结构中 - 所以 Staff 是顶层,然后 HomeWorker 是下一层。所以打字员实际上只是直接从 HomeWorker 继承,尽管它也有来自 Staff 的字段,由于层次结构
  • 您是否已经确定staffMember 不为空,所以id 实际上是在您的员工树中找到的,并且返回的实例实际上是Typist

标签: java inheritance instanceof bluej


【解决方案1】:

尝试使用关键字

instanceof

而不是

instanceOf

因为最后一个不是 Java 中的关键字。

【讨论】:

  • +1 表示敏锐的眼光,值得一提的是null instance of Typistfalse :)
  • 确实是这样!谢谢,我没有看到那里的树木。
  • 问题是语法错误。还有一点关于添加一个工作人员确实存在于列表中的检查,当我得到另一个工作时,我打算这样做:-)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-12
  • 2014-11-10
  • 2020-08-30
  • 2022-01-13
  • 2021-02-03
相关资源
最近更新 更多