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