GIGO: words unreadable aloud
Mishrogo Weedapeval
 

 

  Monday 22 November 2004
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   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:42:41 .
Click here to send an email to the editor of this weblog.

November 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        
Oct   Dec

Previous/Next