public class Casting { public static void main(String[] args) { Thing[] things = {new Apple(), new Apple(), new Water()}; for (int i = 0; i < things.length; i++) things[i].eat(); for (int i = 0; i < things.length; i++) { if (things[i] instanceof Water) ((Water) things[i]).swallow(); /*try also this:*/ // things[i].swallow(); // not allowed } } } class Thing { void eat() { System.out.println("Eat "+this.getClass().getName()); } } class Apple extends Thing { } class Water extends Thing{ void swallow() { System.out.println("Swallow "+this.getClass().getName()); } } /* Output: Eat Apple Eat Apple Eat Water Swallow Water */