首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >具有不同方法参数的Java子类

具有不同方法参数的Java子类
EN

Stack Overflow用户
提问于 2018-08-11 04:33:39
回答 1查看 104关注 0票数 0

我正在尝试做一个模拟简单的生物和食肉动物的模拟。

我有一个名为creature的类和一个名为carnCreature的子类。我在生物中有一个名为eat的方法,它接受一种类型的对象,但我需要carnCreature类中的eat方法来接受一个生物列表。我尝试将该方法命名为与生物类中相同的名称,但当我尝试调用它时,java不接受更新后的参数。

代码语言:javascript
复制
package simulationObjects;

import java.awt.Color;
import java.util.List;
import java.util.Random;

import java.lang.Math.*;

public class Creature {

    public int x;
    public int y;

    public int maxTilesX;
    public int maxTilesY;

    public Color color;

    public float health = 50;
    public int life = 0;

    public Creature (int x, int y, Color color, int maxTilesX, int maxTilesY) {
        this.x = x;
        this.y = y;
        this.color = color;
        this.maxTilesX = maxTilesX;
        this.maxTilesY = maxTilesY;
    }

    public void update(Tile tile) {
        eat(tile);
        life++;
        health-=1;
    }


    public void eat(Tile currentTile) {
        if (currentTile.color == this.color) {
            health += 3;
            currentTile.color = Color.GRAY;
        }  
    }

    public boolean isCarnivore() {
        return false;
    }
}




package simulationObjects;

import java.awt.Color;
import java.util.List;

public class CarnCreature extends Creature{


    private static final boolean CANABOLIC = false;

    public CarnCreature(int x, int y, Color color, int maxTilesX, int maxTilesY) {
        super(x, y, color, maxTilesX, maxTilesY);
        // TODO Auto-generated constructor stub
    }

    public void update(List<Creature> creatures) {
        eat(creatures);
        life++;
        health-=1;
    }

    public void eat(List<Creature> creatures) {
        for (Creature creature : creatures) {
            if (CANABOLIC) {
                if (creature.color == this.color) {
                    health += 3;
                    creature.health = 0;
                } 
            } else {
                if (creature.color == this.color && creature.isCarnivore() == false) {
                    health += 3;
                    creature.health = 0;
                }
            }

        }

    }

    public boolean isCarnivore() {
        return true;
    }

}

稍后将调用eat函数,如下所示:

代码语言:javascript
复制
    for (Creature creature : creatures) {
        if (creature.isCarnivore()) {
            creature.upadte(creatures);
        } else {
            creature.update(tiles.get(creature.x).get(creature.y));
        }
    }

我正在尝试将这些生物和carnCreatures存储在同一个列表中,即“生物”。这就是问题所在吗?我是否需要将它们存储在单独的列表中?

谢谢

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-08-11 04:44:42

你有两个选择:

  • 一旦你知道这个生物是否是食肉动物,就可以使用它并访问方法
  • 创建一个具有相同“签名”的方法,即相同的名称和参数。

第二种选择是更优雅的。使用多态性的“魔力”,每个类都会调用它的方法,并且不需要使用isCarnivore()方法检查类。但是你需要从图块中获取生物的列表。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/51793729

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档