1

the thing I would like to know is how to write an enhanced for loop for an array based on the class of the object in the array. I understand how to do a for loop based on index number like if it's odd or even but I'm looking for based on class. Example:

Array[] Kind = new Array[3];
Kind[0] = new Fruit(xxx,yyy,zzz)
Kind[1] = new Veg(xxx,yyy,zzz)
Kind[2] = new Fruit(xxx,yyy,zzz)
Kind[3] = new Veg(xxx,yyy,zzz)

Fruit and Veg classes are created and extended from the Kind class. I need to write a FOR loop that out puts something for Fruit and something different for Veg.

3
  • stackoverflow.com/questions/7313559/… Commented Oct 25, 2014 at 0:49
  • Erm... fruit and veg should know how to deal with this. In general, if you're checking instanceof then something has gone wrong with your OO design. Commented Oct 25, 2014 at 0:53
  • Kind is a class? The way you wrote it, Array is your class and Kind is a variable name. Also, you allocated only 3 elements in your array and you're trying to assign to 4, so you will get an out-of-bounds exception. Maybe you mean Kind[] array = new Kind[4]; and then set array[0] = ... Commented Oct 25, 2014 at 0:56

1 Answer 1

1

First, you need to fix your program: rather than declaring an array of arrays Array[], declare an array of base classes Kind, like this:

Kind[] kind = new Kind[4];
kind[0] = new Fruit(xxx,yyy,zzz);
kind[1] = new Veg(xxx,yyy,zzz);
kind[2] = new Fruit(xxx,yyy,zzz);
kind[3] = new Veg(xxx,yyy,zzz);

Now if you would like to print different things for Fruit and Veg subclasses of Kind, override toString of the two classes as needed. This would let you go through instances of your base class Kind, and printing would be dispatched to the method in the appropriate class:

public class Fruit extends Kind {
    @Override
    public string toString() {
        return "Fruit "+ ... // Fill in the text that you wish to print
    }
}
public class Veg extends Kind {
    @Override
    public string toString() {
        return "Veg "+ ... // Fill in the text that you wish to print
    }
}

Printing can be done like this:

for (Kind item : kind) {
    System.out.println(item.toString());
}

The call of toString() above is optional - you can call System.out.println(item); as well. I added the call of toString() to show that there is no "magic" in there.

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

2 Comments

You've reproduced the OP's error of initializing the array to only hold 3 objects instead of the 4 given.
@Blazto Not when you're initializing. You initialize to the length. [3] is 3 objects at [0],[1],[2].

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.