Search code examples
javainheritanceextendsinstanceof

JAVA: How to compare child class in a List


So I created a parent class : Animals

public class Animals {

   private String type;

   public String getType(){
       return this.type;
   }
}

And I then created different child class like horse, bear, dog etc that extends Animals.

I then created a List < Animals > list which can contain object which are either from horse class, bear, etc.

But I've been struggling to create a method that could tell me if yes or no my list contains for i.e any bear (an object from Bear Class).

I tried so many things.

  1. horse.getClass() returns nothing

  2. if i do a

     Horse h = new Horse();
    

    System.out.print(h instanceof Bear);

---> it returns true which is wrong.

  1. Same thing with equals.
  2. I also created a String attribute in each child class so I can compare the string instead but Java doesn't read them as string somehow.

I am so lost.


Solution

  • The issue is with your if statement.

    if(a instanceof Bear);
        return true;
    

    You have ended your if statement with a semicolon which means its an empty statement and the next line return true is always executed. Remove the semicolon after the if statement.

    Read more here: Semicolon at end of 'if' statement