【问题标题】:Calling of subclass methods in heritance [closed]在继承中调用子类方法[关闭]
【发布时间】:2017-11-04 12:54:41
【问题描述】:

我有一个类 Customer,它由 RichPerson 类和 PoorPerson 类继承。它存储在 ArrayList cus 中……但是,一些子类方法不同,我在访问 Customer 数组列表时无法调用子类方法.. 像 cus.get(0).description..

【问题讨论】:

标签: java object arraylist


【解决方案1】:

您必须将其转换为 RichPerson:

RichPerson rp = (RichPerson) cus.get(0);
//you can use rp.description

要检查类型,您可以使用instanceof 运算符:

if(cus.get(0) instanceof RichPerson) {
    RichPerson rp = (RichPerson) cus.get(0);
}

【讨论】:

  • 为什么它被否决了?它有效..我读了一些帖子说它不鼓励这样做..
猜你喜欢
  • 1970-01-01
  • 2012-05-11
  • 1970-01-01
  • 1970-01-01
  • 2014-05-10
  • 1970-01-01
  • 2021-10-21
  • 2021-06-17
  • 1970-01-01
相关资源
最近更新 更多