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.

Blazto
  • 43
  • 1
  • 9
  • http://stackoverflow.com/questions/7313559/what-is-the-instanceof-operator-used-for – Joren Oct 25 '14 at 00: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. – Jon Kiparsky Oct 25 '14 at 00: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] = ` ... – ajb Oct 25 '14 at 00:56

1 Answers1

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.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
  • You've reproduced the OP's error of initializing the array to only hold 3 objects instead of the 4 given. –  Oct 25 '14 at 01:05
  • @Blazto Not when you're initializing. You initialize to the length. [3] is 3 objects at [0],[1],[2]. –  Oct 25 '14 at 03:12