43.scala编程思想笔记——基类初始化

43.scala编程思想笔记——基类初始化

欢迎转载,转载请标明出处:http://blog.csdn.net/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"

在导出类中,通过为基类构造器调用提供必需的构造器参数,可以在导出类的主构造器中调用任何重载的基类构造器。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值