GIGO: words unreadable aloud
Mishrogo Weedapeval
 

 

  Tuesday 18 May 2004
Chapter 4, Exercises 1-2 revisited

The exercise for c4x1 requests: "Create a class with a default constructor (one that takes no arguments) that prints a message. Create an object of this class."

A few days ago, I wrote up Exercises 1-2 of Chapter 4, but still had questions about how to make a default (no-argument) contructor. The answer showed up yesterday on the Scala mailing list: the no-argument constructor is simply the body of the class. Here are the simpler, more java-like solutions to those two exercises.

(The corresponding THECLAPP entries are here and here.)

class c4x1c_deM {
    Console.println( "    ... creating a c4x1c_deM, default ctor." );
}
object c4x1_deM {
    def main ( args: Array[String] ) = {
        Console.println( "Declaring a c4x1c_deM 'o' ..." );
        val o = new c4x1c_deM;
        Console.println( "All done." );
    }
}

C4x2 the exercise: "Add an overloaded constructor to Exercise 1, that takes a String argument and prints it along with your message."

class c4x2c_deM {
    Console.println( "    ... creating a c4x2c_deM, default ctor." );
    def this ( i:Int ) = {
        this();
        Console.println( "c4x2c_deM Int ctor, with argument " + i );
    }
}
object c4x2_deM {
    def main ( args: Array[String] ) = {
        Console.println( "Declaring a plain c4x2c_dem 'o' ..." );
        val o = new c4x2c_deM;
        Console.println( "Declaring a c4x2c_dem 'p' (1) ..." );
        val p = new c4x2c_deM(1);
        Console.println( "All done." );
    }
}

(The "deM" part of the class names is today's date, in my short date-stamp form described here.)
8:32:22 AM   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:39:33 .
Click here to send an email to the editor of this weblog.

May 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          
Apr   Jun

Previous/Next