斯卡拉(Scala):为什么我们不能做super.val? [英] Scala : Why can't we do super.val?
问题描述
我正在从JavaTpoint练习这段代码以学习Scala中的继承.但是,我无法从值初始化为零的Vehicle类中访问成员Bike.我尝试通过超级类型引用进行操作,但它仍显示覆盖的值.为什么不允许访问超类字段并定向到覆盖的子类字段(速度).这是代码和输出. 预先感谢.
I am practicing this code from JavaTpoint for learning inheritance in Scala. But I cannot access the member Bike from the class Vehicle who's value is initialized to zero. I tried by super type reference but it still shows the overridden value. Why does it not allow to access the super class field and directs to the overridden sub class field (speed) . here is the code and the output. Thanking in advance.
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()
}
}
推荐答案
众所周知, Scala 编译后, Scala 将被传输到 Java字节码,它与 JVM 兼容.
As we know, after Scala compile, Scala will be transfered to Java bytecode, it's for compatible with JVM.
对于类Vehicle
变量val speed
,在对其子类Bike
(protected
变量)进行编译后可见后,我们可以查看Vehicle
的bytecode
:
And for the class Vehicle
variable val speed
, after compile it's visible for it's subclass Bike
(the protected
variable), we can view the bytecode
of Vehicle
:
public Vehicle();
Code:
0: aload_0
1: invokespecial #63 // Method java/lang/Object."<init>":()V
4: aload_0
5: bipush 10
7: putfield #13 // Field speed:I
10: return
我们可以看到,它是Vehicle
构造函数方法中speed
的值 10 .
As we can see, it's init the speed
's value 10 in the Vehicle
constructor method.
,我们还可以在Bike
构造函数方法中找到init动作:
and we also can find the init action in Bike
constructor method:
public Bike();
Code:
0: aload_0
1: invokespecial #67 // Method Vehicle."<init>":()V
4: aload_0
5: bipush 100
7: putfield #13 // Field speed:I
10: return
在构造函数方法中为speed
设置100
.
it's setting 100
for speed
in constructor method.
因此,当init
Bike
对象时,speed
字段的值已更新为superclass
Vehicle
中的100
.因此super.val
在那里毫无意义.
so when init
the Bike
object, the speed
field's value has been updated to 100
in the superclass
Vehicle
. so super.val
will not make sense in there.
,还有另一件事需要注意:当您直接在子类Bike
中使用super.speed
时,编译器将抛出:
and there is another thing need to call out: when you use the super.speed
directly in your subclass Bike
, the compiler will throw:
super may not be used on value speed
因此引发此编译器错误也是由上述原因引起的.
so this compiler error thrown is also caused by the above reason.
这篇关于斯卡拉(Scala):为什么我们不能做super.val?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!