I am having trouble understanding ((Edible)objects[i]).howToEat() at line 7 in the java code example given below. Edible is an interface which contains abstract method howToEat() and I understand that this is a reference to an array but how is the "Edible" interface being referenced in this statement?
public class TestEdible {
public static void main(String[] args) {
Object[] objects = {new Tiger(), new Chicken(), new Apple()};
for (int i= 0; i <objects.length; i++) {
if(objects[i] instanceof Edible) {
System.out.println( ((Edible)objects[i]).howToEat() );
}
else {
System.out.println("Object is not edible");
}
}
}
}
Please explain if the interface is being referenced from an object or array in the statement, or if this is just a syntax related to interfaces that I may not be familiar with. I am not well versed in use of interfaces so I may be overlooking something, thank you.
((Edible)objects[i])
syntax means cast objects[i]
to Edible
. It could be just (Edible)objects[i]
. It's wrapped into brackets just to inline it for the following method call.
So the code
if(objects[i] instanceof Edible) {
System.out.println( ((Edible)objects[i]).howToEat() );
}
could be rewritten as simpler to read:
if(objects[i] instanceof Edible) {
Edible currentObject = (Edible) objects[i];
System.out.println(currentObject.howToEat());
}
So you're basically telling the Java compiler that you want to threat object[i]
as an Edible
because you know what you do and you already checked it with instanceof
above.
As @daniu noted, with Java 16 you can have another syntax for that:
if(objects[i] instanceof Edible currentObject) {
System.out.println(currentObject.howToEat());
}