Chapter 6, Exercise 4
4. Inherit a new class from class Detergent. Override scrub() and add a new method called sterilize().
The Detergent class is in the chapter, in Java. For this exercise, I just put it into my "x" package that all of my exercises are in, and compiled the java. Then the following scala code does the trick (not that it's much of a trick).
See http://theclapp.blog-city.com/read/19326.htm for Larry's version.
Notes: You have to say override explicitly. I think that adds a huge amount to the readability of O-O code. And note that I chose to make my "sterilize" interface different from most of the other methods, in that my "sterilize" doesn't require the empty parens to call it. I haven't yet decided how much I like that capability, but it's certainly bad style in this particular case, since it makes calls to sterilize look different from calls to any other method.
package x;
class Tide extends Detergent {
override def scrub () = {
append(" ch06_ex04.scrub()");
super.scrub();
}
// add a method to the interface
def sterilize : unit = append(" sterilize()");
}
object c6x4 {
// test the new class
def main ( args : Array[String] ) = {
val x = new Tide;
W.rn("Testing the new Tide class:");
x.dilute();
x.apply();
x.scrub();
x.sterilize;
x.foam();
W.rn("Testing the base (\"Detergent") class: ");
Detergent.main(args);
}
}
11:35:35 PM