The method should return the value of type Animal. In case something goes wrong, and i want to indicate that there is an error, what is the right technique? In case i don't want to raise an error. What can i return instead of type Animal?
public static Animal make_child(Animal a, Animal b) {
// Create a child if both animals of different male
Animal c;
if (a.male == b.male) {
return null;
}
c = new Animal(...);
}
CodePudding user response:
I would suggest using exception handling for this type of issue, here is a link https://www.javatpoint.com/exception-handling-in-java, but if you don't want to use it, you can just return null as you did in your exception above. When you will call the method and the answer will be null, you will be able to make the difference between the right Animal and the wrong one. As example:
//do you really want this method static?
public static Animal make_child(Animal a, Animal b) {
// Create a child if both animals of different male
Animal c;
if (a.male == b.male) {
return null;
}
c = new Animal(...);
}
public static void isNewbornBoyOrGirl(Animal a, Animal b) {
Animal newborn = make_child(a,b);
if(newborn == null)
{
System.out.println("An error has occured!");
return;
//if the newborn is null, a print will be displayed and afterward it will exit the current method
}
// do stuff with newborn as it is not null after calling the method above
}
CodePudding user response:
If something goes wrong you should throw an exception.
throw new Exception("Something went wrong.")
I would recommend you to get familiar with exception handling here: https://www.baeldung.com/java-exceptions
CodePudding user response:
Аdd in class Animal a class field which will indicate if something goes wrong.
Or you can create a subclass EmptyAnimal which extends Animal, create and return this type, and check return value like this
Animal newborn = make_child(a,b);
if (newbor instanceof EmptyAnimal){
System.out.println("something goes wrong");
}
