如何编写在继承类中搜索值的if语句?

时间:2016-11-23 11:22:58

标签: java

我连接了涉及继承的赋值,我正在尝试编写一个if语句,用于搜索特定值是否为true。如果该值对于if语句正在查找的内容为true,我想抛出异常,如果不是,我只想返回该值。到目前为止,这是我的代码:

子类

public class Carnivore extends Animal
{
   public Food eat(Food x) throws Exception
    {
        if (x.equals("Plants")) {
                throw new Exception("Carnivores only eat meat!");
            } else {
                return x;
            }

    }
    public void makeNoise()  
    {
        noise = null;
    }
    public String getNoise()  
    {
        return noise;
    }   
}

超级

abstract public class Animal 
{

String name;
int age;  
String noise;

abstract public void makeNoise();

public String getName() {
        return name;
    }

    public void setName(String newName) {
        name = newName;
    }

abstract public Food eat(Food x) throws Exception;

}

我坚持的部分正在改写:

if (x.equals("Plants")) {
                throw new Exception("Carnivores only eat meat!");
            } else {
                return x;
            }

食品类

public class Food {

    //field that stores the name of the food
    public String name; 

    //constructor that takes the name of the food as an argument
    public Food(String name){
        this.name = name;
    }

    public String getName() {
        return name;
    }
}

如果x的值是"植物"我想这样做。 (这是以String格式键入的)然后抛出异常,否则返回值。任何帮助将不胜感激,谢谢。

0 个答案:

没有答案
相关问题