44.scala编程思想笔记——覆盖方法
欢迎转载,转载请标明出处:blog.csdn.net/notbaron/ar…
源码下载连接请见第一篇笔记。\
当开发覆盖方法时,继承就变得有趣了。例如:
import com.atomicscala.AtomicTest._
class GreatApe {
def call ="Hoo!"
var energy =3
def eat() = {energy += 10; energy }
defclimb(x:Int) = energy -= x
}
class Bonobo extends GreatApe {
override defcall = "Eep!"
// Modify thebase-class var:
energy = 5
// Call thebase-class version:
override defeat() = super.eat() * 2
// Add a newmethod:
def run() ="Bonobo runs"
}
class Chimpanzee extends GreatApe {
override defcall = "Yawp!"
override defeat() = super.eat() * 3
def jump ="Chimp jumps"
val kind ="Common" // New field
}
def talk(ape:GreatApe) = {
//ape.run() // Not an ape method
// ape.jump// Nor this
ape.climb(4)
ape.call +ape.eat()
}
talk(new GreatApe) is "Hoo!9"
talk(new Bonobo) is "Eep!22"
talk(new Chimpanzee) is "Yawp!27"
如果在导出类中创建和基类中完全一样的方法签名,那么就是在用新的行为替换基类中定义的行为,这称为覆盖。
使用super关键字,即超类的缩写。