I apologize if the title of this doesn't make much sense. I have this sample of code from Y. Daniel Liang's
Introduction to Java Programming, 6th ed., that I don't understand. This code is given as an example of how to create a custom interface, which is "Edible." If an object is "Edible," it has a method that returns a String that tells how to eat it.
I have this first part in Edible.java:
public interface Edible {
public String howToEat();
}
This next part is in TestEdible.java
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++)
showObject(objects);
}
public static void showObject(Object object) {
if (object instanceof Edible)
System.out.println(((Edible)object).howToEat());
}
}
class Animal {
}
class Chicken extends Animal implements Edible, Comparable {
int weight;
public Chicken(int weight) {
this.weight = weight;
}
public Chicken() {
}
public String howToEat() {
return "Fry it";
}
public int compareTo(Object o) {
return weight - ((Chicken)o).weight;
}
}
class Tiger extends Animal {
}
abstract class Fruit implements Edible {
}
class Apple extends Fruit {
public String howToEat() {
return "Make apple cider";
}
}
class Orange extends Fruit {
public String howToEat() {
return "Make orange juice";
}
}What I don't understand is why you need to cast the object on line 10. Shouldn't the if statement (line 9) make sure that the particular object currently being tested is "Edible" or not, and therefore not require any casting?