Chapter 7, Exercise 7
Back from the Coleman Columbia's maiden voyage (to Big Sur). A successful trip, that I'll write about once I get the time to upload the photos. Even towing a tent-trailer for the first time ever, it's under two hours from home to the campground that's just downhill from the Ventana Inn. We oughta get down there more often.
Ok, so Exercise 7 says to Modify Exercise 6 so that Rodent is an abstract class. Make the methods of Rodent abstract whenever possible. .
First, I just applied this simple diff:
10,13c10,13
< class Rodent( s: String ) {
< var rname : String = s;
< def chew = W.rn( rname + " chews." );
< def poop = W.rn( rname + " poops." );
---
> abstract class Rodent( s: String ) {
> val rname : String = s;
> def chew : Unit; // abstract
> def poop : Unit; // abstract
just to see what the error messages looked like. Here:
c7x7.scala:19: class Gerbil needs to be abstract, since method poop in class Rodent is not defined
class Gerbil extends Rodent("Gerbil") {
^
c7x7.scala:22: class Hamster needs to be abstract, since method chew in class Rodent is not defined
class Hamster extends Rodent("Hamster") {
^
c7x7.scala:25: class Capybara needs to be abstract, since method poop in class Rodent is not defined
class Capybara extends Rodent("Capybara") {
^
three errors found
That was pretty straightforward.
So, fixed those and removed the poop, to get this:
package x;
abstract class Rodent( s: String ) {
val rname : String = s;
def chew : Unit; // abstract
def scurry = W.rn( rname + " scurries." );
}
class Mouse extends Rodent("Mouse") {
override def chew = W.rn( rname + " chews cheese." );
override def scurry = W.rn( rname + " scurries TO DISNEYLAND." );
}
class Gerbil extends Rodent("Gerbil") {
override def chew = W.rn( rname + " chews argee." );
override def scurry = W.rn( rname + " scurries in place." );
}
class Hamster extends Rodent("Hamster") {
override def chew = W.rn( rname + " chews honeybaked." );
}
class Capybara extends Rodent("Capybara") {
override def chew = W.rn( rname + " chews gauchos." );
override def scurry = W.rn( rname + " scurries the samba." );
}
// A "factory" that randomly creates rodents:
class RandomRodentGenerator {
private var rand = new java.util.Random();
def next : Rodent = {
rand.nextInt(4) match {
case 0 => new Mouse;
case 1 => new Gerbil;
case 2 => new Hamster;
case 3 => new Capybara;
}
}
}
object c7x7 {
private var gen = new RandomRodentGenerator;
def main ( args: Array[String] ) = {
var s = new Array[Rodent]( 9 );
for( val i <- Iterator.range(0, s.length) )
s(i) = gen.next;
for( val i <- Iterator.range(0, s.length) ) {
s(i).chew; s(i).scurry
}
}
}
In scala, the syntax for definitions (def with an equals sign) is different enough from the syntax for declarations (def with just a type) that the abstract keyword isn't needed for members.
11:31:03 PM