GIGO: words unreadable aloud
Mishrogo Weedapeval
 

 

  Wednesday 25 August 2004
Chapter 7, Exercise 6

Not much different from the Shapes example from earlier this month. I did discover how to declare a class so that its constructor argument is required. So I'll have to revisit this entry, and probably others.

Create an inheritance hierarchy of Rodent: Mouse, Gerbil, Hamster, etc. In the base class, provide methods that are common to all Rodents, and override these in the derived classes to perform different behaviors depending on the specific type of Rodent. Create an array of Rodent, fill it with different specific types of Rodents, and call your base-class methods to see what happens.

Here's the code:

package x;
class Rodent( s: String ) {
    var rname : String = s;
    def chew = W.rn( rname + " chews." );
    def poop = W.rn( rname + " poops." );
}
class Mouse extends Rodent("Mouse") {
    override def chew = W.rn( rname + " chews cheese." );
    override def poop = W.rn( rname + " poops pellets." );
}
class Gerbil extends Rodent("Gerbil") {
    override def chew = W.rn( rname + " chews rgere." );
}
class Hamster extends Rodent("Hamster") {
    override def poop = W.rn( rname + " poops in its cage." );
}
class Capybara extends Rodent("Capybara") {
    override def chew = W.rn( rname + " chews gauchos." );
}
// 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 c7x6 {
    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).poop;
        }
    }
}

11:59:04 PM   comment/     


Click here to visit the Radio UserLand website. Click to see the XML version of this web page. © Copyright 2007 Doug Landauer .
Last update: 07/2/6; 12:41:37 .
Click here to send an email to the editor of this weblog.

August 2004
Sun Mon Tue Wed Thu Fri Sat
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30 31        
Jul   Sep

Previous/Next