I am writing a program that demonstrates the use of inheritance and overriding methods. I want to create an if statement that involves the use of an exception. I ave included the exception in my if statement but when I write "throws exception" a the beginning of the method, I m getting n error message that says ""overridden method does not throw Exception". Here is the code:
Sub class
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;
}
}
Super class
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);
}
Any help on how to re-write this so that the exception is thrown properly is appreciated, thanks.