43.scala编程思想笔记——基类初始化
欢迎转载,转载请标明出处:http://blog.youkuaiyun.com/notbaron/article/details/50447590
源码下载连接请见第一篇笔记。
Scala通过确保所有构造器都会被调用来保证正确的对象创建过程:不仅对象导出类的构造器会被调用,基类的构造器也会被调用。
如果基类有构造器参数,那么任何继承自该类的类都必须在构造过程中提供这些参数。
例如:
import com.atomicscala.AtomicTest._
class GreatApe(
valweight:Double, val age:Int)
class Bonobo(weight:Double, age:Int)
extendsGreatApe(weight, age)
class Chimpanzee(weight:Double, age:Int)
extendsGreatApe(weight, age)
class BonoboB(weight:Double, age:Int)
extendsBonobo(weight, age)
def display(ape:GreatApe) =
s"weight: ${ape.weight} age: ${ape.age}"
display(new GreatApe(100, 12)) is
"weight: 100.0 age: 12"
display(new Bonobo(100, 12)) is
"weight: 100.0 age: 12"
display(new Chimpanzee(100, 12)) is
"weight: 100.0 age: 12"
display(new BonoboB(100, 12)) is
"weight: 100.0 age: 12"
从GreatApe继承时,Scala会强制传递构造器参数给GreatApe基类。
在Scala对对象内存之后,会首先调用基类的构造器,然后是基类的直接导出类的构造器,最终一直调用到导出类的构造器为止。
如果基类中有辅助构造器,那么可以选择改为调用这些构造器中的某一个。
如下:
import com.atomicscala.AtomicTest._
class House(val address:String,
valstate:String, val zip:String) {
defthis(state:String, zip:String) =
this("address?",state, zip)
defthis(zip:String) =
this("address?", "state?", zip)
}
class Home(address:String, state:String,
zip:String,val name:String)
extendsHouse(address, state, zip) {
overridedef toString =
s"$name: $address, $state $zip"
}
class VacationHouse(
state:String,zip:String,
valstartMonth:Int, val endMonth:Int)
extendsHouse(state, zip)
class TreeHouse(
valname:String, zip:String)
extendsHouse(zip)
val h = new Home("888 N. Main St.","KS",
"66632", "Metropolis")
h.address is "888 N. Main St."
h.state is "KS"
h.name is "Metropolis"
h is
"Metropolis: 888 N. Main St., KS 66632"
val v =
newVacationHouse("KS", "66632", 6, 8)
v.state is "KS"
v.startMonth is 6
v.endMonth is 8
val tree = new TreeHouse("Oak","48104")
tree.name is "Oak"
tree.zip is "48104"
在导出类中,通过为基类构造器调用提供必需的构造器参数,可以在导出类的主构造器中调用任何重载的基类构造器。