我有一个class它有一个ArrayList在它与它的逻辑,我们称之为胃.
来自的两个实例class Meal和Drinks正在添加到ArrayList我的中的实例Main class.这两个类有一个覆盖方法返回getName()方法.
但是在我执行所有操作class的ArrayList地方,我不能使用foreach循环来使用对象的toString()方法ArrayList.
public void amountOfElements() {
for (Digestion d : stomach) {
//prints the hash code. I can't call the corresponding toString() equivalent in here.
System.out.println(d);
}
Run Code Online (Sandbox Code Playgroud)
我尝试Stomach class在我拥有的地方创建一个属性ArrayList并从中调用方法,但我得到了一个NullPointerException因为名称尚不存在.
我必须以这种方式解决它,因为实现了返回名称的方法.
提前致谢.