Instructor: Dan Shiovitz
Name: _____________________________________________________________
Object
class.protected
members are
not visible outside the class and are not
inherited.private
members are not
inherited, but protected
ones are.super
can be used to
call the parent's constructor.
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 + " o'clock"; } public void sound() { System.out.println("tick-tock"); } }
toString
method that displays both the
current hour and the alarm hour
Reasonably straightforward, I hope:
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 Clock(7); clockBox[count++] = new AlarmClock(3, 6); clockBox[count++] = new Clock(3); clockBox[count++] = new AlarmClock(12,12); for (int i = 0; i < count; i++) { System.out.println(clockBox[i]); clockBox[i].sound(); }
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:
7 o'clock tick-tock 3 o'clock, alarm set to 6 o'clock tick-tock 3 o'clock tick-tock 12 o'clock, alarm set to 12 o'clock ring ring