In Java to create a mutable property cost, you need to define a field cost and a getter and setter:
public class Car { private int cost; public Car(int c) { this.cost = c; System.out.println("This comes First " + getCost()); } public int getCost() { return cost; } public void setCost(int cost) { this.cost = cost; } }
Kotlin has the concept of a property embedded in the language, so you can achieve the same with only creating a var property as you did:
open class Car(c : Int){ open var cost : Int = c init { println("This comes First $cost") } }
This is much more concise from the developer perspective, but the implementation is the same. Kotlin compiler is generating a field cost, a get method and set method for us under the hood. Now the interesting part. When you make the cost property in the parent class open and overrides it in the child class, you are actually overriding the get method. It is not possible to override a field, neither in Kotlin nor Java.
As @Pawel mentioned in his answer that's the java code for the Vehicle child class:
public class Vehicle extends Car { private int cost = 20000; @Override public int getCost() { return this.cost; } @Override 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()); } }
When you execute println("This comes First $cost") in the parent class, you are actually executing System.out.println("This comes First " + getCost()); and the actual getCost() being called is the one in the child class Vehicle. As the child class cost field has not been initialized yet, as we are still executing the super(cc) call, its value is zero.
cost: Intinstead ofcost : Int.