-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?

3
  • 2
    Please provide some Java code as example, not just some pseudo-code. Commented May 26, 2017 at 12:28
  • you need to loop and then check the type via instanceof for example. Commented May 26, 2017 at 12:29
  • Please paste code relevant to fields you are talking about in issue. Commented May 26, 2017 at 12:29

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

3 Comments

instanceof and getClass().equals() are not equivalent. So the first example will print also the subclasses, while the second will not.
Yes, it will. However, I have just given both the ways it can be checked.
No, it won't. x.getClass().equals(Flying.class) is true only if x is of type Flying, not of a subclass of it.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.