I am new to scala from java and am confused by the sequence of initializing the scala object in my own hierarchy. IIRC, in Java, if a subclass object is initialized, the constructor of its base class is called before any code of its own constructor. In scala, I get a completely different behavior. Consider the following example:
class Point(val x: Int, val y: Int){ val name = this.makeName; def makeName: String = { println("makeName at super."); "[" + x + ", " + y + "]"; } override def toString: String = name; } class ColorPoint(override val x: Int, override val y: Int, var color: String) extends Point(x, y) { // key statement println(name); override def makeName: String = { println("makeName at sub."); super.makeName + ":" + myColor; } val myColor = color; override def toString: String = name; }
Let's just take a look at the byte code of the ColorPoint
constructor dumped with javap
. If the code contains a println(name);
key operator println(name);
then byte code
public ColorPoint(int, int, java.lang.String); Code: 0: aload_0 1: aload_3 2: putfield #13;
We see that the myColor
field myColor
initialized after invokespecial
, that is, after the initialization of the base class.
If I comment on the println(name);
statement println(name);
, then the byte code:
public ColorPoint(int, int, java.lang.String); Code: 0: aload_0 1: aload_3 2: putfield #13;
We see that the myColor
field myColor
initialized immediately before invokespecial
, i.e. before initializing the database.
Then what is the reason? Does any document / article define this type of behavior?
BTW, my scala version is 2.7.7final (OpenJDK Server VM, Java 1.6.0_20). Thanks and best regards!