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