如何使用 sub class 的实例访问 super class 的成员
How to access members of super class using an instance of the sub class
我正在练习 JavaTpoint 中的这段代码,以学习 Scala 中的继承。但是我无法从值初始化为零的 class Vehicle 访问成员 Bike。我尝试了超类型引用,但它仍然显示覆盖值。你能告诉我如何使用 Bike class 的实例访问值 speed = 0 吗?这是代码和输出。
提前致谢。
class Vehicle{
val speed = 0
println("In vehicle constructor " +speed)
def run(){
println(s"vehicle is running at $speed")
}
}
class Bike extends Vehicle{
override val speed = 100
override def run(){
super.run()
println(s"Bike is running at $speed km/hr")
}
}
object MainObject3{
def main(args:Array[String]){
var b = new Bike()
b.run()
var v = new Vehicle()
v.run()
var ve:Vehicle=new Bike()
println("SuperType reference" + ve.speed)
ve.run()
}
}
我可以想到两个选项。
1) 在覆盖之前保存该值。
class Bike extends Vehicle{
val oldspeed = speed
override val speed = 100
override def run(){
println(s"Vehicle started at $oldspeed km/hr")
println(s"Bike is running at $speed km/hr")
}
}
2) 在基数class中使值成为def
。然后就可以在子class.
中访问了
class Vehicle{
def speed = 0
def run(): Unit = {...}
}
class Bike extends Vehicle{
override val speed = 100
override def run(){
println(s"Vehicle started at ${super.speed} km/hr")
println(s"Bike is running at $speed km/hr")
}
}
我正在练习 JavaTpoint 中的这段代码,以学习 Scala 中的继承。但是我无法从值初始化为零的 class Vehicle 访问成员 Bike。我尝试了超类型引用,但它仍然显示覆盖值。你能告诉我如何使用 Bike class 的实例访问值 speed = 0 吗?这是代码和输出。 提前致谢。
class Vehicle{
val speed = 0
println("In vehicle constructor " +speed)
def run(){
println(s"vehicle is running at $speed")
}
}
class Bike extends Vehicle{
override val speed = 100
override def run(){
super.run()
println(s"Bike is running at $speed km/hr")
}
}
object MainObject3{
def main(args:Array[String]){
var b = new Bike()
b.run()
var v = new Vehicle()
v.run()
var ve:Vehicle=new Bike()
println("SuperType reference" + ve.speed)
ve.run()
}
}
我可以想到两个选项。
1) 在覆盖之前保存该值。
class Bike extends Vehicle{
val oldspeed = speed
override val speed = 100
override def run(){
println(s"Vehicle started at $oldspeed km/hr")
println(s"Bike is running at $speed km/hr")
}
}
2) 在基数class中使值成为def
。然后就可以在子class.
class Vehicle{
def speed = 0
def run(): Unit = {...}
}
class Bike extends Vehicle{
override val speed = 100
override def run(){
println(s"Vehicle started at ${super.speed} km/hr")
println(s"Bike is running at $speed km/hr")
}
}