我正在編寫一個基於繼承演示的程序。我正在嘗試編寫一個異常,以便唯一可以傳遞到鏈接到Wolf類的Meat類的參數。本質上,我試圖讓唯一可以傳入進食方法的參數成爲一個名爲Meat的Food變量。下面是代碼:如何傳遞需要參數類型爲Food的參數?
動物
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;
}
食品
public class Food {
//field that stores the name of the food
public Food name;
//constructor that takes the name of the food as an argument
public Food(Food name){
this.name = name;
}
public Food getName() {
return name;
}
}
肉類
public class Meat extends Food
{
public Meat(Food name)
{
super(name);
}
public Food getName()
{
return super.getName();
}
}
食肉動物
public class Wolf extends Carnivore
{
Wolf()
{
name = "Alex";
age = 4;
}
public void makeNoise()
{
noise = "Woof!";
}
public String getNoise()
{
return noise;
}
public String getName()
{
return name;
}
public int getAge()
{
return age;
}
public Food eat(Food x) throws Exception
{
if (x instanceof Meat) {
return x;
} else {
throw new Exception("Carnivores only eat meat!");
}
}
}
狼
public class Wolf extends Carnivore
{
Wolf()
{
name = "Alex";
age = 4;
}
public void makeNoise()
{
noise = "Woof!";
}
public String getNoise()
{
return noise;
}
public String getName()
{
return name;
}
public int getAge()
{
return age;
}
public Food eat(Food x) throws Exception
{
if (x instanceof Meat) {
return x;
} else {
throw new Exception("Carnivores only eat meat!");
}
}
}
主要
public class Main {
public static void main(String[] args)
{
Wolf wolfExample = new Wolf();
System.out.println("************Wolf\"************");
System.out.println("Name = " + wolfExample.getName());
System.out.println("Age = " + wolfExample.getAge());
wolfExample.makeNoise();
System.out.println("Noise = " + wolfExample.getNoise());
Meat meatExample = new Meat(//Food argument goes here?);
System.out.println("************Wolf eating habits************");
System.out.println("Wolves eat " + wolfExample.eat(meatExample.getName()));
}
}
我遇到的問題是,我不能在任何通作中新食品的說法我在主要方法中創建的肉類對象。當我試圖調用System.out.println("Wolves eat " + wolfExample.eat(meatExample.getName()));
時,我得到了一個不受支持的異常的錯誤,我認爲這可能是因爲Food變量沒有被傳入。期望的結果是傳遞了一個Food變量,例如Plants,它將引發異常消息。任何幫助如何解決這個表示讚賞,謝謝。
你應該修復你搞砸的縮進。 – khelwood
只是傳遞meatExample而不是meatExample.getName()。 –
'肉類肉類例子=新肉類(//食物爭論在這裏?)'仍然需要食物論證來傳遞,我仍然不確定。 – James