Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Can some explane to me what is the instanceof in java? For example: I have this

ID: 3652855 • Letter: C

Question

Can some explane to me what is the instanceof in java? For example: I have this method public boolean willEat(Animal anim) { if(anim instanceof Wolf) { return false; } else if(anim instanceof Bird) { return true; } else if(anim instanceof Worm){ return false; } else if( anim == null){ return false; } return false; } this method is overriding from the superclass called Animal this method is in a subclass called Wolf, and the Wold should eat Bird, which is also a subclass. this method should specify that the Wolf eats Bird, Is what I did correct? Please any help

Explanation / Answer

The instanceof keyword is very self explanatory: it is used to test if an object is an instance of a particular class. Example: // Make a new String object String str = "123"; // Display a message if str is a String if (str instanceof String) { System.out.println("str is a String!"); } Of course, the above isn't very useful since we already know str is a String. So let's look at another example: public static void f(Object obj) { if (obj instanceof String) { System.out.println("obj is a String!"); } else { System.out.println("obj is NOT a String!"); } } In this example, we have no idea what type of object obj will be. So we test to see if obj is a String or not. The instanceof keyword was more useful in the past (before Java 1.5) when Java didn't have the idea of generic types in it. Now it's generally considered bad practice to use the instanceof keyword, since it means we don't know what type of objects we're using.