Why am I not catching this exception properly? - java

I'm trying to catch an Exception that should show an error message but doesn't seem to be doing so. I have made another block of code that is exactly the same apart from the changes of some variable names and that catches an exception but this one doesn't seem to be doing so. The purpose of the exception is that the program should look for a Plant object and if it is not found it should throw an exception to show that herbivores only eat plants. Here is the relevant pieces of code:
Main method
import java.util.logging.Level;
import java.util.logging.Logger;
public class Main {
public Main() {
super();
}
Rabbit rabbitExample = new Rabbit();
public static void main(String[] args) {
Rabbit rabbitExample = new Rabbit();
System.out.println("************EXCEPTION 2************");
try {
Food pork = new Food("Prok");
System.out.println("************Herbivore caught Exception example************");
System.out.println("Exception caught");
rabbitExample.eat(pork);
//wolfExample.eat(vegFood);
} catch (Exception e) {
// TODO: Add catch code
e.printStackTrace();
}
try {
System.out.println("************Herbivore non-caught Exception example************");
Food vegiFood = new Plant("Vegetables"); // you create a Meat object and store it in a Food variable (so to speak)
System.out.println("Herbivores eat " + rabbitExample.eat(vegiFood)); // must be surrounded by a try-catch block
}
catch (Exception ex) {
// TODO: Add catch code
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);;
}
}
}
Animal 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) throws Exception;
}
Rabbit class
public class Rabbit extends Herbivore
{
Rabbit()
{
name = "Haryy";
age = 2;
}
public void makeNoise()
{
noise = "Squeek!";
}
public String getNoise()
{
return noise;
}
public String getName()
{
return name;
}
public int getAge()
{
return age;
}
public String eat(String Food)
{
return Food;
}
public Food eat(Food x) throws Exception
{
if (x.equals(new Plant("Meat"))) {
throw new Exception("Herbivores only eat plants!");
} else {
return x;
}
}
}
Herbivore class
public class Herbivore extends Animal
{
public Food eat(Food x) throws Exception
{
if (x.equals(new Plant("Meat"))) {
throw new Exception("Herbivores only eat plants!");
} else {
return x;
}
}
public void makeNoise()
{
noise = "Woof!";
}
public String getNoise()
{
return noise;
}
}
Food class
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;
}
#Override
public String toString() {
return name;
}
}
I apologist about the amount of code displayed but I wanted to show all relevant code required in order to run the program. The output is as displayed:
************EXCEPTION 2************
************Herbivore caught Exception example************
Exception caught
************Herbivore non-caught Exception example************
Herbivores eat Vegetables
Whereas the output should be:
************EXCEPTION 2************
************Herbivore caught Exception example************
Exception caught
java.lang.Exception: Herbivores only eat plants!
************Herbivore non-caught Exception example************
Herbivores eat Vegetables
Any help is appreciated, thanks.

Hetre is your problem:
public Food eat(Food x) throws Exception
{
if (x.equals(new Plant("Meat"))) {
throw new Exception("Herbivores only eat plants!");
} else {
return x;
}
}
Your Food subclass does not overwrite equals() (and hashcode()). The default implementation in class Object merrily does a == compare which is always false for different objects even if they are logically the same.
But resist the temptation to implement equals() (and hashcode()) in class Food. only concrete classes (classes you create objects from) can really tell if some other object is equal.

This if (x.equals(new Plant("Meat"))) will always yield false (unless the x parameter is passed as null) , therefore your exception will never be triggered because new Plant create a new reference in memory and it can't be equal to an an already existing reference

Related

Is it possible to have a different super(message) be displayed for a customException?

I have a custom exception class InvalidNameException that is supposed to handle an error if the input string either is too short or has any special characters.
I was wondering if it is possible to have a different super(message) be displayed based on what condition the input name satisfies.
It should ideally look like this but since super(message) needs to be the first message in a constructor, I am curious in knowing if this is something that can be done or do I need to find another way to achieve this.
The customException class looks like this
class InvalidNameException extends Exception
{
public InvalidNameException(String name) {
if(validName(name)){
super("Name Contains Special Characters");
}
else if(validLength(name)){
super("Name is too long");
}
}
public boolean validName(String name){
boolean check = true;
for (int i = 0; i < name.length(); i++) {
if (!Character.isLetter(name.charAt(i))
&& !Character.isWhitespace(name.charAt(i))) {
check = false;
}
}
return check;
}
public boolean validLength(String name){
boolean check = true;
if(name.length()<6) {
check = false;
}
return check;
}
}
You cannot call super twice. To make this work, you would have to throw a new exception for each condition like this:
public InvalidNameException(String name) throws Exception {
if(validName(name)){
throw new Exception("Name Contains Special Characters");
}
else if(validLength(name)){
throw new Exception("Name is too long");
}
}
Let's go back to beginning and say(my comment wasn't clear, sorry about that), you can have different super(message) by defining methods as static.
class InvalidNameException extends Exception {
public static InvalidNameException ofName(String name) {
if (validName(name)) {
return new InvalidNameException("Name Contains Special Characters");
}
if (validLength(name)) {
return new InvalidNameException("Name is too long");
}
return null;
}
private InvalidNameException(String message) {
super(message);
}
public static boolean validName(String name){
...
}
public static boolean validLength(String name){
...
}
}
By doing this, however, since exception instance is generated conditionally, you have to write another validation on calling function. Its output is not clear enough that you can easily make a mistake like NullPointerException.
public void foobarMethod(String name) throws InvalidNameException {
InvalidNameException exception = InvalidNameException.ofName(name);
if (exception != null) {
throw exception;
}
}
Plus, InvalidNameException is defining error but also validating the data. This is the point where I said roles are become unclear.
My suggestion is to define setter method inside class that holds name(for say, Person), since storing and validating have deeper connection with each other than exception definition.
class InvalidNameException extends Exception {
private final String name;
public String getName() {
return this.name;
}
private InvalidNameException(String name, String message) {
super(message);
this.name = name;
}
public static InvalidNameException invalidCharacter(String name) {
return new InvalidNameException(name, "Name Contains Special Characters");
}
public static InvalidNameException invalidLength(String name) {
return new InvalidNameException(name, "Name is too long");
}
}
class Person {
private String name;
public void setName(String name) throws InvalidNameException {
if (validName(name)) {
throw InvalidNameException.invalidCharacter(name);
}
if (validLength(name)) {
throw InvalidNameException.invalidLength(name);
}
this.name = name;
}
public static boolean validName(String name){
...
}
public static boolean validLength(String name){
...
}
}
class Foobar {
public void insertPerosn(String name) {
try {
Person person = new Person();
person.setName(name);
} catch (InvalidNameException e) {
System.out.println(e.getMessage());
System.out.println("Your input is: " + e.getName());
}
}
}
There's no perfect answer for this, but at least this is my opinion.

How do I throw an exception in my Java code?

I got a method that prints out the animals' names.
I now need an error to be printed out if the id is not one of the given ones.
How does it work?
class Methode {
static final int DEER = 0;
static final int BIRD = 1;
static final int COW = 2;
static final int PIG = 3;
public static void main(String[] args) {
printAnimal();
}
public static void printAnimal (int id) {
if (id == DEER) {
System.out.println("Deer");
}
else if (id == BIRD) {
System.out.println("Bird");
}
else if (id == COW) {
System.out.println("COW");
}
else if (id == PIG) {
System.out.println("Pig");
}
}
}
If by error you mean an Exception (otherwise I don't know why you didn't simply printed an "error" message like you did in your else if branches), then you need to create a custom class which extends Exception and throw it in a new else branch. Here is an example:
Exception:
public class NoSuchAnimalException extends Exception {
public NoSuchAnimalException(String message) {
super(message);
}
}
Test:
public static void printAnimal(int id) throws NoSuchAnimalException {
if (id == DEER) {
System.out.println("Deer");
} else if (id == BIRD) {
System.out.println("Bird");
} else if (id == COW) {
System.out.println("COW");
} else if (id == PIG) {
System.out.println("Pig");
} else {
throw new NoSuchAnimalException("No such animal");
}
}
public static void main(String[] args) {
try {
printAnimal(6);
} catch (NoSuchAnimalException e) {
System.out.println(e.getMessage());
}
}
The exception will be thrown in the last else (the id provided in method call doesn't meet the previous requirements) and will be handled in the public static void main() method.
Firstly you call your printAnimal() method without a parameter. That's no good.
Secondly, there are two kinda of exceptions in Java, checked and unchecked. You need to consider which kind you're working with.
Checked means your function must be declared by:
methodName() throws SomeException{
...}
And accordingly a caller MUST catch exceptions.
Unchecked means you can throw the exception without doing this, but other programmers aren't made aware of (and conversely, not forced to handle) any exceptions thrown.
Exceptions should be created, like classes, inheriting the base type of exception appropriate.
Checked exception
class someException extends exception{...}
Unchecked exception
class someException extends RuntimeException{...}
For non custom exceptions they are thrown like so:
The checked exception
throw new Exception ('message');
The unchecked exception
throw new RuntimeException ('message');
Please read the Java doc on exceptions.
Exceptions are an important part of OOP
(This was written on a phone, so there might be a few typos etc.)
Should use enums and switch for this task:
public class Methode {
public enum Animal {
DEER (0),
BIRD (1),
COW (2),
PIG (3);
private final int value;
private static Map valueMap = new HashMap<>();
Animal(int value)
{
this.value = value;
}
static {
for (Animal enumVal : Animal.values()) {
valueMap.put(enumVal.value, enumVal);
}
}
public static Animal valueOf(int animalId) {
return (Animal) valueMap.get(animalId);
}
public int getValue()
{
return value;
}
}
public static void main(String[] args) throws Exception {
printAnimal(1);
}
public static void printAnimal (int id) throws Exception {
Animal animal = Animal.valueOf(id);
if(animal == null) {
throw new Exception("Animal not found"); //better use own exception
} else {
switch (animal) {
case DEER:
System.out.println("Deer");
break;
case BIRD:
System.out.println("Bird");
break;
case COW:
System.out.println("COW");
break;
case PIG:
System.out.println("Pig");
break;
default:
System.out.println(animal.name());
}
}
}
}

How can i prevent explicit casting if you want to use properties of the sub-type?

So the compiler complains when ever i do a explicit cast. I can prevent this by using a #SuppressWarnings annotation.
At this point i would have this annotation a lot in my code which lets me suspect that there is another way i'm just not aware of.
Lets have a look at this example
class CutePet
{
public void pet()
{
System.out.println( "The cute pet gets some pets" );
}
}
class Cat extends CutePet
{
public void letOutside()
{
System.out.println( "The cat goes outside" );
}
public void letInside()
{
System.out.println( "The cat comes inside" );
}
public void removeTick()
{
System.out.println( "The cat looses all ticks" );
}
}
class Dog extends CutePet
{
public void goForAWalk()
{
System.out.println( "The Dog goes for a walk" );
}
public void tellHimWhatHeIs()
{
System.out.println( "The Dog is a good boy" );
}
}
class caretaker
{
public void takeCare( CutePet pet )
{
if( pet instanceof Cat )
{
pet.pet();
((Cat)pet).letOutside();
((Cat)pet).letInside();
((Cat)pet).removeTick();
}
else if( pet instanceof Dog )
{
pet.pet();
((Dog)pet).goForAWalk();
((Dog)pet).tellHimWhatHeIs();
}
}
}
The Caretaker does not know what kind of Pet he will get in advance and he my has several pets of different kinds.
I tried to give the Cute pet class a getType() method which returns a enum. With this enum i can remove the "instanceof" but the cast is still there.
Am i missing something?
If this were a real world problem, the caretaker would recognize which kind of pet he has based on the pet's appearance. While "instance of" is one way of looking at it, you might want to consider overloading the takeCare method directly with the subtypes as required. For example:
class Caretaker {
public void takeCare(Cat pet) {
pet.pet();
pet.letOutside();
pet.letInside();
pet.removeTick();
}
public void takeCare(Dog pet) {
pet.pet();
pet.goForAWalk();
pet.tellHimWhatHeIs();
}
}
in other words, the caretaker knows what to do (has methods already in place) for the kind of pet he receives.
EDIT
In response to some of the comments, yes, the original example shifts the problem further up. If you have an array or a list of generic pets then you still have to figure out what kinds of pets you have to give them to the caretaker. Conceptually it seems strange that the pet should be able to pet itself, take itself for a walk, etc. (these methods are part of the pet class when it should be the caretaker doing these actions ON the pet).
I've since rewritten the code with a full working example below with a Job class that has a perform method. This method will return the appropriate job based on the type of animal the caretaker has. The caretaker can then perform the job on the pet in question. See below.
Doing things this way avoids instanceof. While it is debatable how good/bad instanceof actually is, where possible it should be the object itself to tell me what it needs, otherwise the whole polymorphism concept can get pretty hairy pretty quick.
import java.util.Arrays;
public class Test {
public static void main(String[] args) {
Caretaker caretaker = new Caretaker();
Arrays.asList(
new Cat("Cat1"),
new Cat("Cat2"),
new Dog("Dog1")
).forEach(caretaker::takeCare);
}
interface CutePet {
String whoAmI();
Job whatINeed();
}
abstract static class NamedCutePet implements CutePet {
private final String name;
public NamedCutePet(String name) {
this.name = name;
}
public String whoAmI() {
return this.name;
}
}
static class Cat extends NamedCutePet {
public Cat(String name) {
super(name);
}
#Override
public Job whatINeed() {
return new CatJob(this);
}
}
static class Dog extends NamedCutePet {
public Dog(String name) {
super(name);
}
#Override
public Job whatINeed() {
return new DogJob(this);
}
}
static class Caretaker {
void takeCare(CutePet pet) {
pet.whatINeed().perform();
}
}
static abstract class BaseJob implements Job {
void pet(CutePet pet) {
System.out.println(String.format("The cute pet %s gets some pets", pet.whoAmI()));
}
}
static class DogJob extends BaseJob {
private final Dog dog;
public DogJob(Dog dog) {
this.dog = dog;
}
#Override
public void perform() {
pet(dog);
takeDogFarAWalk(dog);
tellHimWhatHeIs(dog);
}
private void takeDogFarAWalk(Dog dog) {
System.out.println(String.format("The dog %s goes for a walk", dog.whoAmI()));
}
private void tellHimWhatHeIs(Dog dog) {
System.out.println(String.format("The dog %s is a good boy", dog.whoAmI()));
}
}
static class CatJob extends BaseJob {
private final Cat cat;
public CatJob(Cat cat) {
this.cat = cat;
}
#Override
public void perform() {
pet(cat);
letOutside(cat);
letInside(cat);
removeTick(cat);
}
private void letOutside(Cat cat) {
System.out.println(String.format("The cat %s goes outside", cat.whoAmI()));
}
private void letInside(Cat cat) {
System.out.println(String.format("The cat %s comes inside", cat.whoAmI()));
}
private void removeTick(Cat cat) {
System.out.println(String.format("The cat %s loses all ticks", cat.whoAmI()));
}
}
interface Job {
void perform();
}
}
Let's make it clear: you can't call subclass specific methods without typecasting to subclass type.
Now, let me suggest an alternate way. Define a method takeCare() in the superclass and let the subclasses implement it by calling several specific methods specific to subclasses. Then from CareTaker#takeCare(), call only takeCare() method without typecasting.
Several other alternate approaches can be used to solve the situation.
Here is how you would do it with interfaces and reflection. Note that only the interface methods are called for each pet type. It could also be extended to call other methods.
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class PetProblem {
public static void main(String[] args) {
Caretaker caretaker = new Caretaker();
Dog dog = new Dog();
caretaker.takeCare(dog);
System.out.println("\nNow do it for the cat\n");
Cat cat = new Cat();
caretaker.takeCare(cat);
}
}
interface CuteCat {
void letOutside();
void letInside();
void removeTick();
}
interface CuteDog {
void goForAWalk();
void tellHimWhatHeIs();
}
interface CutePet {
default void pet() {
System.out.println("The cute pet gets some pets");
}
}
class Cat implements CutePet, CuteCat {
public void letOutside() {
System.out.println("The cat goes outside");
}
public void letInside() {
System.out.println("The cat comes inside");
}
public void removeTick() {
System.out.println("The cat looses all ticks");
}
}
class Dog implements CutePet, CuteDog {
public void goForAWalk() {
System.out.println("The Dog goes for a walk");
}
public void tellHimWhatHeIs() {
System.out.println("The Dog is a good boy");
}
}
class Caretaker {
public void takeCare(Object pet) {
Class<?>[] ifss = pet.getClass().getInterfaces();
for (Class<?> ifs : ifss) {
Method[] methods = ifs.getDeclaredMethods();
for (Method m : methods) {
try {
m.invoke(pet);
}
catch (IllegalAccessException | InvocationTargetException e) {
e.printStackTrace();
}
}
}
}
}
Note however, that using interfaces and having a method so named that it can be used for all pets is easier. Here is an example. Since both dogs and cats need to eat, a common method feedMe() can be implemented for each.
public class AnimalShelter {
public static void main(String[] args) {
Caretaker caretaker = new Caretaker();
Dog dog = new Dog();
Cat cat = new Cat();
caretaker.feedThePets(dog);
caretaker.feedThePets(cat);
}
}
interface SupperTime {
void feedMe();
}
class Caretaker {
public void feedThePets(SupperTime pet) {
pet.feedMe();
}
}
class Dog implements SupperTime {
public void feedMe() {
System.out.println("Oh boy, Kibbles n' Bits");
}
}
class Cat implements SupperTime {
public void feedMe() {
System.out.println("Yum. Purina Cat Chow");
}
}

How to throw exceptions using inherited classes?

For my assignment, I am trying to throw an exception so that my program does not allow objects "Wolf" to eat "Plants". I am however struggling to find a way to implement this. I have so far tried using an if statement to search for the condition of food (x) being equal to "Plants" but this does not seem to be working. Here is the code:
Animal 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) throws Exception;
}
Food class
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;
}
}
Carnivore class
public class Carnivore extends Animal
{//if statement that throws exception
public Food eat(Food x) throws Exception
{
if (x.equals(new Meat("Plants"))) {
throw new Exception("Carnivores only eat meat!");
} else {
return x;
}
}
public void makeNoise()
{
noise = null;
}
public String getNoise()
{
return noise;
}
}
Meat class
public class Meat extends Food
{
public Meat(String name) {
super(name);
}
public String getName() {
return super.getName();
}
}
Wolf class
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 String eat(String x)
{
return x;
}
}
Main
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("Plants");
System.out.println("************Wolf eating habits************");
System.out.println("Wolves eat " + wolfExample.eat(meatExample.getName()));
}
}
Output
************Wolf"************
Name = Alex
Age = 4
Noise = Woof!
************Wolf eating habits************
Wolves eat Plants//this should throw exception message
Any help on how to fix this to get the desired output would be greatly appreciated, thanks.
This code is causing the problem:
if (x.equals(new Meat("Plants"))) {
throw new Exception("Carnivores only eat meat!");
} else {
return x;
}
You don't have a equals method defined in your classes, so it compares objects using == operator - checking if the references are the same.
This expression:
x == (new Meat("Plants"))
is always false - new operator creates new instance of Meat object so the reference is always different.
Do not use equals to check types, use instanceof operator instead.
So your code should look like this:
public Food eat(Food x) throws Exception
{
if (x instanceof Meat) {
return x;
} else {
throw new Exception("Carnivores only eat meat!");
}
}
In that case you will need to define Plant class that extends Food.
Alternatively you can define equals method in your Food class that compares name field.
How to override equals method in java

How to pass an argument that requires a parameter of type Food?

I am writing a program that is based on the demonstration of inheritance. I am trying to write an exception so that the only parameter that can be passed into the Meat class which is linked to the class Wolf. In essence, I am trying to allow the only parameter that can be passed into the eating method to be a Food variable called Meat. Here is the code:
Animal
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;
}
Food
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;
}
}
Meat
public class Meat extends Food
{
public Meat(Food name)
{
super(name);
}
public Food getName()
{
return super.getName();
}
}
Carnivore
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!");
}
}
}
Wolf
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!");
}
}
}
Main
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()));
}
}
The problem I'm having is that I cannot pass in anything as a food argument within the new Meat object that I create within my main method. And I mm getting the error of an unsupported exception when I try to call System.out.println("Wolves eat " + wolfExample.eat(meatExample.getName()));which I think may be because a Food variable has not been passed in. The desired outcome is that a Food variable such as Plants is passed in which throws an exception message. Any help on how to resolve this is appreciated, thanks.
You will have to modify your Animal and Food classes first and then with few other changes in your Main class, you may be able to achieve what you are trying to. Here are few suggested changes:
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;
}
}
public class Meat extends Food
{
public Meat(String name) {
super(name);
}
public String getName() {
return super.getName();
}
}
public class Main {
public Main() {
super();
}
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());
try {
Meat meatExample = new Meat("Steak");
//Food vegFood = new Food("Spinach");
System.out.println("************Wolf eating habits************");
wolfExample.eat(meatExample);
//wolfExample.eat(vegFood);
} catch (Exception e) {
// TODO: Add catch code
e.printStackTrace();
}
}
}
So, If you call wolfExample.eat(vegFood); your code will throw exception.
First of all, your Carnivore class and Wolf class is same.
You have not passed name for your 'meatExample'
And try instantiating Meat object and assign it in Food class
Food meatExample = new Meat("Beef");
This way you are calling getName() method of Food class rather than from Meat class.
Basically, your Food and Meat class design is incorrect, which needs to be fixed as shown below i.e., Meat class should take the argument of food name property.
Food class:
public abstract class Food {
//field that stores the name of the food
protected String name;
public String getName() {
return this.name;
}
}
Meat class:
public class Meat extends Food {
public Meat(String name) {
super.name = name;
}
//other methods or add other specific meat fields
}
main() method:
public static void main(String[] args) {
//Create the Meat Object by sending the name in constructor
Meat meatExample = new Meat("Chicken");
//other code
}

Categories

Resources