我正在尝试将值传递给构造函数并打印值。
open class Car(c : Int){
open var cost : Int = c
init {
println("This comes First $cost")
}
}
open class Vehicle(cc : Int) : Car(cc) {
override var cost : Int = 20000
init {
println("This comes Second $cost")
}
fun show(){
println("cost = $cost")
}
}
fun main() {
var vehicle = Vehicle(1000)
vehicle.show()
}
输出
This comes First 0
This comes Second 20000
cost = 20000
如果我只是对此行发表评论override var cost : Int = 20000
输出为
This comes First 1000
This comes Second 1000
cost = 1000
您是否查看了生成的字节码并尝试将其反编译回Java?如果您经常对Kotlin的工作原理感到困惑,可以帮助您理解。
在这种情况下,您的Java类将如下所示(我反编译了您的代码并对其进行了一些清理):
public class Car {
private int cost;
public int getCost() {
return this.cost;
}
public void setCost(int var1) {
this.cost = var1;
}
public Car(int c) {
this.cost = c;
System.out.println("This comes First " + getCost());
}
}
public class Vehicle extends Car {
private int cost = 20000;
public int getCost() {
return this.cost;
}
public void setCost(int var1) {
this.cost = var1;
}
public final void show() {
System.out.println("cost = " + getCost());
}
public Vehicle(int cc) {
super(cc);
System.out.println("This comes Second " + getCost());
}
}
[发生的只是open var
只是对Vehicle
覆盖的setter和getter的声明。那时它不再指向Car.cost
,所以从超级构造函数中登录:This comes First 0
返回Vehicle.cost
的初始化值,这就是为什么您得到0的原因。