-3

In my program I have 4 classes zoo, animal, aquatic and flying.

Zoo uses an array of animal class objects. Aquatic and flying extends the animal class.

This is just an example

CLASS FIELDS

ANIMAL

-name

AQUATIC

-environment

FLYING

-number of wings

If I want to print only the flying type.

FOR i=0 TO total number of animals CHANGEBY 1
    IF (Animal[i].getEnvironment).equals(land)
        OUTPUT Flying.toString()

Can I do something like this?

Draken
  • 3,134
  • 13
  • 34
  • 54
ak5874
  • 1

1 Answers1

0

if I want to print only the flying type

Yes, you can do this using instanceof operator.

if(Animal[i] instanceof Flying){
System.out.println("Ohh Yeah!! I can fly.");
}

Note : The above code will print the output if Animal[i] passes the IS-A Flying test; that means Flying or it's subclass .

OR

if(Animal[i].getClass().equals(Flying.class)) {
System.out.println("Ohh Yeah!! I can fly.");
}

Note : The above code will print output if and only of Animal[i] is Flying but NOT SUBCLASS.

Mehraj Malik
  • 14,872
  • 15
  • 58
  • 85
  • 1
    `instanceof` and `getClass().equals()` are [not equivalent](https://stackoverflow.com/a/4989843/2814308). So the first example will print also the subclasses, while the second will not. – SantiBailors May 26 '17 at 12:48
  • Yes, it will. However, I have just given both the ways it can be checked. – Mehraj Malik May 26 '17 at 12:49
  • No, it won't. `x.getClass().equals(Flying.class)` is true only if `x` is of type `Flying`, not of a subclass of it. – SantiBailors May 29 '17 at 09:56