public class LoudToy { public void makeNoise() { System.out.println("Generic sound!"); } } public class ToyRobot extends LoudToy { public void makeNoise() { System.out.println("BEEP BEEP!"); } public void recharge() { System.out.println("Recharging... Fully charged!"); } } public class ToySheep extends LoudToy { public void makeNoise() { System.out.println("Baah. Baah."); } } /** * Simple examples of polymorphism and dynamic binding. * * @author Nathan Sprague * */ public class ToyMain { public static void main(String args[]) { badCastingExample(); } public static void nonPolymorphism() { ToyRobot robot; robot = new ToyRobot(); robot.makeNoise(); robot.recharge(); } public static void polymorphismAndDynamicBinding() { LoudToy toy; toy = new ToySheep(); toy.makeNoise(); toy = new ToyRobot(); toy.makeNoise(); //toy.recharge(); // Won't compile, even though toy contains a ToyRobot. } public static void castingExample() { LoudToy toy; toy = new ToyRobot(); toy.makeNoise(); // This cast is OK. toy does contain a ToyRobot. ToyRobot robot = (ToyRobot)toy; robot.recharge(); } public static void badCastingExample() { LoudToy toy; toy = new ToySheep(); toy.makeNoise(); // Compiles, but will cause a run-time error. ToyRobot robot = (ToyRobot)toy; robot.recharge(); } }