I have an array of 10 items in Java (item is a class). Only 4 out of the 10 implement the Breakable
interface.
I'd like to iterate over the array, and if the item is Breakable - do item[i].break()
;
public static Item[] createItems()
{
return new Item[]{
new PaintBoard("PaintyBoardy", 1000, 545,600),
new Lamp("Lampy", 2000,300),
new Glass("Sharpy", 200, 1000),
new Ball("Roundy", 150, "Black"),
new PaintBoard("secondPainty", 1001, 545,600),
new Lamp("Lumpy", 2000,300),
new Glass("Sharper", 200, 1000),
new Ball("Circular", 150, "Black"),
new PaintBoard("Boardy", 1000, 545,600),
new Lamp("Limpy", 2000,300)
};
This is the method I use to create my array. Only Lamp and Glass implements the Breakable
interface.
I've tried sending the item[i]
to a method
public static void breakItem (Breakable item)
{
item.Break();
}
I've tried casting (Breakable)item[i].break();
, nothing seems to work.
You can use an instanceof
check and a cast:
for (final Item item : createItems()) {
if (item instanceof Breakable) {
((Breakable) item).break();
}
}
In newer version of Java, the type check and the cast can be combined:
for (final Item item : createItems()) {
if (item instanceof Breakable breakable) {
breakable.break();
}
}