I am newbie in kotlin, I trying to apply lesson on oop on
I don't know where's error in this code
open class Car( open val color:String?=null, open val brand:String?=null) {
open fun speed(){
println("max speed is 220")
}
}
class Toyota() : Car() {
override color = "White"
override brand = "Toyota"
override fun speed(){
println("max speed is 360")
}
}
fun main() {
var car:Toyota = Toyota()
car.speed()
}
CodePudding user response:
You are missing a val
keyword in both parameters in Toyota
class:
class Toyota() : Car() {
override val color = "White"
override val brand = "Toyota"
override fun speed(){
println("max speed is 360")
}
}
Or you can do it even better by using Car
constructor directly:
class Toyota : Car(color = "White", brand = "Toyota") {
override fun speed(){
println("max speed is 360")
}
}
With this approach you can even make Car
simpler (no need for open
keyword on your properties):
open class Car(val color : String? = null, val brand : String? = null) {
open fun speed(){
println("max speed is 220")
}
}
CodePudding user response:
You could override color and brand in the constructor of the subclass:
class Toyota(override val color: String = "White", override val brand: String = "White") : Car() {
override fun speed() {
println("max speed is 360")
}
}