为什么kotlin中的属性重写会使主要构造函数属性为零

问题描述 投票:2回答:1

我正在尝试将值传递给构造函数并打印值。

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概念进行比较,以便在此处进行更好的解释
java kotlin inheritance constructor overriding
1个回答
0
投票

您是否查看了生成的字节码并尝试将其反编译回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的原因。

© www.soinside.com 2019 - 2024. All rights reserved.