繁体   English   中英

无法在初始化为超类的 ArrayList 中调用派生类的方法

[英]Unable to call derived class's method in ArrayList initialized to super class

我正在通过Java学习面向对象的编程,正在编写一个冰箱程序来练习。 在我的程序中,有一个带有两个派生类 PerishableItem 和 LeftoverItem 的 Item 类。 我创建了一个初始化为 Item 的 ArrayList,并向 ArrayList 添加了 PerishableItem 和 LeftoverItem。 问题是我无法在派生类中调用不在 Item 类中的方法。

ArrayList<Item> itms = new ArrayList<Item>();

itms.add(new Item("apple", 0.45, new Date(1, 1, 2001)));
itms.add(new LeftoverItem("rice", 9.99, new Date(1, 1, 2001), 3));
itms.add(new PerishableItem("yogurt", 4.48, new Date(1, 1, 2001), 5));

System.out.println(itms.get(2).getDaysToExpire()); // error here

getDaysToExpire() 是 PerishableItem 类中的方法,而不是 Item 类中的方法。 似乎编译器甚至根本没有看到该方法。 谢谢!

Item还应该有方法getDaysToExpire () 来工作...但是当您调用它们时,派生类中的正确getDaysToExpire () 将被调度。

另一种方法是将items.get(2)类型转换为PerishableItem ,然后调用getDaysToExpire ,但这绝对不是一个好的设计。

冰箱中的任何物品都有有效期,所以,我不明白为什么在 Item 类中也没有这个方法。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM