0

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.

  • You must be doing something wrong with your tests or class hierarchy because the thing you labelled '2' will not return true. What is the class declaration for the `Horse` and `Bear` class? – Ben Anderson Mar 05 '22 at 22:08
  • @BenAnderson I have nothing inside my class except this: `public class Bear extends Animals { private String type = "bear"; } I created my list inside another model Class public class Cell { private List contents = new ArrayList(); public List getCellContents(){ return contents; } public boolean hasBear(){ for(int i=0; i< contents.size(); ++i){ Animals a = contents.get(i); if(a instanceof Bear); return true; } return false; }` – Todoroki Attack Mar 05 '22 at 22:35
  • possible that the fact you have done `++i` instead of `i++` is causing issues – Ben Anderson Mar 05 '22 at 22:54

1 Answers1

0

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