Nathan Sprague
/**
* Class representing a generic loud toy.
* Exists only to serve as a superclass.
*/
public class LoudToy
{
public void makeNoise()
{
// This should be overridden in subclasses.
System.out.println("Generic noise.");
}
}
public class ToyRobot extends LoudToy
{
private int chargeLevel;
public ToyRobot()
{
chargeLevel = 5;
}
@Override
public void makeNoise()
{
System.out.println("Beep Beep!");
}
public void recharge()
{
chargeLevel = 10;
System.out.println("Charged up!");
}
}
What will be printed?
ToyRobot robot;
robot = new ToyRobot();
robot.makeNoise();
robot.recharge();
|
|
What will be printed?
LoudToy toy;
toy = new ToySheep();
toy.makeNoise();
toy = new ToyRobot();
toy.makeNoise();
Generic noise.
Generic noise.
Baaa.
Beep Beep!
Generic noise.
Baaa.
Generic noise.
Beep Beep!
Which code sample will result in the following terminal output?
Beep Beep!
Charged up!
LoudToy toy;
toy = new ToyRobot();
toy.makeNoise();
toy.recharge();
LoudToy toy;
ToyRobot bot;
toy = new ToyRobot();
toy.makeNoise();
bot = toy;
bot.recharge();
LoudToy toy;
ToyRobot bot;
toy = new ToyRobot();
toy.makeNoise();
bot = (ToyRobot)toy;
bot.recharge();
None of the above.
More than one of the above.
LoudToy toy;
ToyRobot bot;
toy = new ToySheep();
bot = (ToyRobot)toy;
bot.makeNoise();
Will it compile? Will it execute without an exception? If so, what will be printed?
One option...
|
|
Protected members are visible in all subclasses (and all other classes in the same package).
|
|
/**
* 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();
}
}
ToyRobot bot = new ToyRobot();
LoudToy toy = bot;
ToySheep sheep = new ToySheep();
PlayUtils.playWithLoudToy(bot);
PlayUtils.playWithLoudToy(toy);
PlayUtils.playWithLoudToy(sheep);