Question:
You are given the following class hierarchy:
public class Animal {
// attributes and methods
}
public class Mammal extends Animal {
// attributes and methods
}
public class Elephant extends Mammal {
// attributes and methods
}
public class ThrowExceptionExample {
public static void checkAnimal(Animal animal) {
// code to check if the animal is a Mammal
// if it is not a Mammal, throw a new IllegalArgumentException with a message "Animal must be a Mammal!"
}
public static void main(String[] args) {
Animal animal1 = new Elephant();
Animal animal2 = new Animal();
// Call checkAnimal method for animal1
// Call checkAnimal method for animal2
}
}
Your task is to complete the checkAnimal
method in the ThrowExceptionExample
class. The method should throw a new IllegalArgumentException
if the animal
parameter is not an instance of the Mammal
class. The exception message should be "Animal must be a Mammal!".
In the main
method, two animal objects are created: animal1
, which is an instance of the Elephant
class, and animal2
, which is an instance of the Animal
class. You need to call the checkAnimal
method for both animal1
and animal2
and handle any exceptions that may be thrown.
Write the code for the checkAnimal
method and handle any exceptions in the main
method. Provide step-by-step detailed explanation of the code.
Answer:
public static void checkAnimal(Animal animal) {
if (!(animal instanceof Mammal)) {
throw new IllegalArgumentException("Animal must be a Mammal!");
}
}
public static void main(String[] args) {
Animal animal1 = new Elephant();
Animal animal2 = new Animal();
try {
checkAnimal(animal1);
System.out.println("animal1 is a Mammal.");
} catch (IllegalArgumentException e) {
System.out.println(e.getMessage());
}
try {
checkAnimal(animal2);
System.out.println("animal2 is a Mammal.");
} catch (IllegalArgumentException e) {
System.out.println(e.getMessage());
}
}
Explanation:
checkAnimal
method takes an Animal
object as a parameter.if
statement checks if the animal
parameter is not an instance of the Mammal
class using the instanceof
operator.animal
is not a Mammal
, an IllegalArgumentException
is thrown with the message "Animal must be a Mammal!".main
method, a try-catch
block is used to handle any exceptions that may be thrown by the checkAnimal
method.animal1
is an instance of the Elephant
class, which is a subclass of Mammal
. So, calling the checkAnimal
method for animal1
will not throw an exception.System.out.println("animal1 is a Mammal.");
is executed, indicating that animal1
is indeed a mammal.animal2
is an instance of the Animal
class, which is not a subclass of Mammal
. So, calling the checkAnimal
method for animal2
will throw an exception.catch
block catches the thrown IllegalArgumentException
and executes the statement System.out.println(e.getMessage());
, which will print the exception message "Animal must be a Mammal!".