/** * Class representing a generic loud toy. * Exists only to serve as a superclass. */ public class LoudToy { private int volume; public LoudToy(int volume) { this.volume = volume; } public void makeNoise() { // This should be overridden in subclasses. System.out.println("Generic noise."); } public int getVolume() { return volume; } } /** * A rechargable toy robot. */ public class ToyRobot extends LoudToy { private int chargeLevel; public ToyRobot() { super(10); chargeLevel = 5; } public void makeNoise() { System.out.println("Beep Beep!"); } public void recharge() { chargeLevel = 10; System.out.println("Charged up!"); } } /** * A toy sheep that says "Baaa." */ public class ToySheep extends LoudToy { public ToySheep() { super(3); } public void makeNoise() { System.out.println("Baaa."); } } /** * Utility methods to help us play with toys. */ public class PlayUtils { public static void playWithLoudToy(LoudToy toy) { System.out.println("This is a fun loud toy!"); toy.makeNoise(); } public static void playWithLoudToy(ToyRobot robot) { System.out.println("This is a fun robot!"); robot.makeNoise(); } } public class ToyDriver { public static void main(String args[]) { overloadedMethodExample(); } 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(); } public static void overloadedMethodExample() { LoudToy toy; ToyRobot robot; robot = new ToyRobot(); toy = robot; // The superclass version will be called... PlayUtils.playWithLoudToy(toy); // The subclass version will be called... PlayUtils.playWithLoudToy(robot); ToySheep sheep; sheep = new ToySheep(); // The superclass version will be called, because // there is no method defined for this subclass. PlayUtils.playWithLoudToy(sheep); } }