Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Referencing an interface from ArrayList

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 ArrayList 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 ArrayList 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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

((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 17 you can have another syntax for that:

if(objects[i] instanceof Edible currentObject) {
   System.out.println(currentObject.howToEat());
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading