【问题标题】:Change an object within ArrayList using a method and return [closed]使用方法更改 ArrayList 中的对象并返回 [关闭]
【发布时间】:2013-11-26 09:28:00
【问题描述】:
public class Egg extends Bee{
    protected boolean eat() {
        return true;
    }

    protected static Object anotherDay() {

        eat();
        if(age>=3)
        {
            Larvae larvae = new Larvae();
            return this;
        }
        age++;
        return this; 
    }
}


public abstract class Bee {
    protected String type;
    protected int age;
    protected int health = 3;

    protected String getType()
    {
        return type;
    }
    protected int getAge()
    {
        return age;
    }
    protected int getHealth()
    {
        return health;
    }

    protected void setAge(int age)
    {
        this.age = age;
    }

    protected abstract boolean eat();
    protected abstract static Object anotherDay();  //the bees tasks for day (should include eat())

}

我正在尝试更改 anotherDay() 方法,以便它返回一个对象,但我不知道如何执行此操作。 然后该对象将替换 arrayList 中的当前对象(arrayList 中的 Egg 对象将在列表中的同一点变成 Larvae 对象) 目前,我发现抽象静态对象返回一个对象,但它不起作用。

【问题讨论】:

  • 我还没有看到任何数组列表,你需要先看看你的设计。
  • 你不能在静态上下文中return this;
  • arrayList 在另一个名为 hive 的类中,而不是从静态返回 this 是我要求另一种方式的原因
  • anotherDay() 最初是一个布尔值,但如果您想知道,我需要更新它以返回一个类
  • @user1642671 anotherDay() 是静态的有什么特别的原因吗?如果没有,则使其成为非静态的。

标签: java arraylist polymorphism return


【解决方案1】:

我会让 anotherDay 方法成为检查年龄的 void 方法,如果它是正确的值,则删除鸡蛋并将幼虫添加到其索引中。

【讨论】:

  • 工作表要求我使用返回方法替换它(这让我感到困惑,或者我会这样做,但谢谢)
猜你喜欢
  • 2012-12-06
  • 2018-08-04
  • 2014-11-17
  • 1970-01-01
  • 2016-09-05
  • 1970-01-01
  • 2016-06-21
  • 1970-01-01
  • 2019-02-18
相关资源
最近更新 更多