Instructor: Dan Shiovitz
Name: _____________________________________________________________
Object
.inherited
keyword.
False. The keyword in question is super
.
The hierarchy, you remember, looks like: A / | \ B C D | | E F
Consider the following class definition:
class Clock { protected int currentHour; public Clock (int h) { currentHour = h; } public String toString() { return currentHour + ":00"; } public void sound() { System.out.println("tick-tock"); } }
toString
method that displays both the
current hour and the alarm hour
class AlarmClock extends Clock { private int alarmHour; public AlarmClock(int h, int ah) { super(h); alarmHour = ah; } public String toString() { return super.toString() + ", alarm set to " + alarmHour + " o'clock"; } public void sound() { if (currentHour == alarmHour) System.out.println("ring ring"); else super.sound(); } }
Clock[] clockBox = new Clock[8]; int count = 0; clockBox[count++] = new AlarmClock(8, 2); clockBox[count++] = new Clock(10); clockBox[count++] = new Clock(4); clockBox[count++] = new AlarmClock(6,6); for (int i = 0; i < count; i++) { clockBox[i].sound(); System.out.println(clockBox[i]); }
The important point here is that even though the array is of Clock objects, Java correctly figures out if it's an AlarmClock object or a Clock object and calls the appropriate method. Also, remember count++ evaluates to count's old value, not its new one. Anyway, the output is:
tick-tock 8 o'clock, alarm set to 2 o'clock tick-tock 10 o'clock tick-tock 4 o'clock ring ring 6 o'clock, alarm set to 6 o'clock