GIGO: words unreadable aloud
Mishrogo Weedapeval
 

 

  Wednesday 26 May 2004
Chapter 4, Exercises 17-18

Chapter 4, Exercise 17

17. Create a class with a static String field that is initialized at the point of definition, and another one that is initialized by the static block. Add a static method that prints both fields and demonstrates that they are both initialized before they are used.

In scala, the body of the class passes for what Bruce is calling a "static block", except that it is static in Scala only because it's inside an object rather than a class.

Here is THECLAPP's c4x17 solution.

package x;
object c4x17 {
    var sdefn : String = "c4x17c sdefn";
    var scons : String = _;
    Console.println( "scala obj main body" );
    scons = "scala static String init" ;
    def main ( args: Array[String] ) = {
        Console.println( "sdefn " + sdefn );
        Console.println( "scons " + scons );
    }
}

Chapter 4, Exercise 18

18. Create a class with a String that is initialized using "instance initialization". Describe a use for this feature (other than the one specified in this book).

In scala, this would just use statements in the main body of the class. Different from the "static block" only in that these statements are in a class, not in a file-level object.

(THECLAPP's c4x18.)

class c4x18c {
    var s1 : String = _;
    s1 = "init in instance init area";
    def demo_init = Console.println( "s1: " + s1 );
}
object c4x18 {
    def main ( args: Array[String] ) = {
        val obj = new c4x18c;
        obj.demo_init;
    }
}

10:41:47 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:39:59 .
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