Scala中的重写字段
Scala字段重写
重写是允许子类重新定义父类成员的概念。在面向对象的编程中,方法和变量/字段都可以被覆盖。在Scala中,方法和字段都可以被覆盖,但是字段的覆盖对实现有一些限制。
Scala中的重写字段
为了重写Scala中的字段,必须牢记一些规则,以避免在实现此概念时出现错误,
要实现概念字段重写,必须使用override关键字。如果您错过了关键字,将提示错误并停止执行代码。
只能覆盖使用val键盘定义的用于定义父类和子类中字段的字段。
使用var关键字定义的字段不能被覆盖,因为它们在类中的任何位置都是可编辑的(即,允许对变量进行读写操作)。
这里有一些程序展示了字段重写和Scala的实现。
1)没有替代关键字的Python程序
如果不使用override关键字,该程序将显示什么输出?
class animal{
val voice = "animal's voice"
}
class dog extends animal{
val voice = "Dog bark's...!"
def says(){
println(voice)
}
}
class cat extends animal{
val voice = "cat meow's...!";
def says(){
println(voice)
}
}
object MainObject{
def main(args:Array[String]){
var ani = new dog()
ani.says()
}
}输出结果
error: overriding value voice in class animal of type String;
value voice needs `override' modifier
val voice = "Dog bark's...!"
^
error: overriding value voice in class animal of type String;
value voice needs `override' modifier
val voice = "cat meow's...!";
^
two errors found2)具有override关键字的Python程序
该程序将显示如果使用override关键字将输出什么?
class animal{
val voice = "animal's voice"
}
class dog extends animal{
override val voice = "Dog bark's...!"
def says(){
println(voice)
}
}
class cat extends animal{
override val voice = "Cat meow's...!";
def says(){
println(voice)
}
}
object MainObject{
def main(args:Array[String]){
var ani = new dog()
ani.says()
var ani2 = new cat()
ani2.says()
}
}输出结果
Dog bark's...! Cat meow's...!
3)使用var关键字的Python程序
该程序将显示如果使用var关键字将输出什么?
class animal{
var voice = "animal's voice"
}
class dog extends animal{
override var voice = "Dog bark's...!"
def says(){
println(voice)
}
}
class cat extends animal{
override var voice = "Cat meow's...!";
def says(){
println(voice)
}
}
object MainObject{
def main(args:Array[String]){
var ani = new dog()
ani.says()
var ani2 = new cat()
ani2.says()
}
}输出结果
error: overriding variable voice in class animal of type String;
variable voice cannot override a mutable variable
override var voice = "Dog bark's...!"
^
error: overriding variable voice in class animal of type String;
variable voice cannot override a mutable variable
override var voice = "Cat meow's...!";
^
two errors found