Created
March 12, 2023 02:31
-
-
Save dzungvu/84e9b4d1908e4da50223446c9b0b5139 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//delegate | |
class DistanceCalculator() { | |
fun calculate(vihecle: Vihecle, time: Float): Float { | |
return vihecle.speed * time | |
} | |
} | |
abstract class Vihecle(open val speed: Float, val model: String) { | |
//use the delegate instead of override travel function in each subclass | |
val distanceCalculator = DistanceCalculator() | |
fun travel(time: Float) { | |
println("$model traveled ${distanceCalculator.calculate(this, time)}") | |
} | |
abstract fun drive() | |
} | |
class Car(override val speed: Float, model: String): Vihecle(speed, model) { | |
override fun drive() { | |
println("Driving a Car") | |
} | |
} | |
class Train(override val speed: Float, model: String): Vihecle(speed, model) { | |
override fun drive() { | |
println("Driving a Train") | |
} | |
} | |
fun main() { | |
val car = Car(60.0f, "Vinfast") | |
car.drive() | |
car.travel(15f) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment