Scala继承中val变量的构造顺序

例子1

class A {
  val x1: String = "hello"
  val x2: String = "mom"
  println("A: x1=" + x1 + ",x2=" + x2)
}

class B extends A {
  override val x2: String = "dad"
  println("B: x1=" + x1 + ",x2=" + x2)
}

object ValTest extends App {
  new A
  println()
  new B
}

输出:

A: x1=hello,x2=mom

A: x1=hello,x2=null
B: x1=hello,x2=dad

 

例子2:

class A {
  val x1: String = "hello"
  val x2: String = x2
  println("A: x1=" + x1 + ",x2=" + x2)
}

class B extends A {
  override val x1: String = "dad"
  println("B: x1=" + x1 + ",x2=" + x2)
}

object ValTest extends App {
  new A
  println()
  new B
}

输出:

A: x1=hello,x2=null

A: x1=null,x2=null
B: x1=dad,x2=null

 

参考 http://blog.iamzsx.me/show.html?id=674002 

posted @ 2015-08-02 15:58  tinylcy  阅读(430)  评论(0编辑  收藏  举报