ch1234
ch1234

Reputation: 17

printing out an array of object

i have a quick question

i have Flying, Aquatic Class extending Animal Class

if i want to only print out Flying objects in the Animal object array

is it safe to just do something like

IF choice is Flying
FOR i=0 TO num CHANGEBY 1 DO
    IF Animal[i] INSTANCEOF Flying THEN
        str = Flying.toString

    END IF
END FOR
OUTPUT str

Or

FOR i=0 TO num CHANGEBY 1 DO
    IF Animal[i] INSTANCEOF Flying THEN
        str = Animal.toString

do this and override the toString method

im new to java so im not even sure if any of these two are right. so any kind of help is welcome

thanks for the help

EDIT-

public static void display(ExampleA[] example)
{ 
    for(int pos = 0; pos < example.length; pos++) 
    {   
        if(example instanceof A)
        {

            output = A.toString()            
        }


    }

    System.out.println(output);

}

sorry for the ambiguous question this is an example of my question

can i do output = A.toString() to get the object string or do i have to do

 output = example.toString()  

and override the toString method to print out the toString in A class as well as Example class

Upvotes: 0

Views: 100

Answers (2)

Mradul Pandey
Mradul Pandey

Reputation: 2054

Hi Your second approach is correct, here is java code for that, You need to implement toString either Parent(Animal) or in Child(Flying) class.

public class Application {

    public static void main(String[] args) {
        Animal arr[] = new Animal[]{new Flying(), new Aquatic(), new Aquatic()};
        for (Animal a : arr) {
            if (a instanceof Flying) {
                System.out.println(a);
            }
        }
    }
}

class Animal {
}

class Flying extends Animal {
    @Override
    public String toString() {
        return "Flying::toString";
    }
}


class Aquatic extends Animal {
}

Upvotes: 1

rajvineet
rajvineet

Reputation: 319

This is not a java code. But considering the logic of question, 1st option looks better choice.

If you have an array of Animal objects in which some are referring to Flying and some are referring to Aquatic, then if you want to call to Flying/Aquatic methods from Animal reference, you should always do a instanceOf check in the if condition then based on child object that animal instance is referring, call the child class method.

Upvotes: 0

Related Questions