Chapter 7, Exercise 12
Twelve: Create a base class with an abstract print() method
that is overridden in a derived class. The overridden version of
the method prints the value of an int variable defined in the
derived class. At the point of definition of this variable,
give it a nonzero value. In the base-class constructor, call
this method. In main(), create an object of the derived type,
and then call its print() method. Explain the results.
That sounds like a program somewhat like this:
package x;
abstract class bcap {
def prin2() : Unit;
W.rn( "bcap Ctor" );
prin2();
}
class c7xGch extends bcap {
var iVar:Int = 27;
override def prin2 () = W.rn( "iVar is " + iVar );
}
object c7xG {
def main ( args : Array[String] ) = {
val c7xGch = new c7xGch;
W.rn( "Before" );
c7xGch.prin2();
W.rn( "After" );
}
}
When I run that, I get:
bcap Ctor
iVar is 0
Before
iVar is 27
After
And a plausible explanation might be that when the base class
(
bcap) constructor is called, Scala already knows that
this is going to be a c7xGch, so it has an iVar and its prin2
function is c7xGch.prin2, but the base class constructor is
executed before the c7xGch constructor, so the iVar is zero
when the base class calls prin2. Then, when the child class
constructor runs, the iVar has been initialized with its 27.
11:32:11 PM