Object-oriented programming examples
Create an object from a class with a constructor property, then read that property.
1class Person(val name: String)
2
3fun main() {
4 val p = Person("Alice")
5 println(p.name)
6}Use a mutable property to update a car’s mileage after it is created.
1class Car(val model: String, var mileage: Int)
2
3fun main() {
4 val car = Car("Toyota", 10000)
5 car.mileage += 500
6 println(car.mileage)
7}Add a secondary constructor that supplies a default name by delegating to the primary constructor.
1class Person(val name: String) {
2 constructor() : this("Unknown")
3}
4
5fun main() {
6 println(Person().name)
7}Use a companion object to provide a factory function that belongs to the class.
1class Person private constructor(val name: String) {
2 companion object {
3 fun named(name: String) = Person(name)
4 }
5}
6
7fun main() {
8 println(Person.named("Alice").name)
9}Extend a base class to give a bike its own property as well as a brand. The open keyword is required because Kotlin classes are final by default, so they cannot be subclassed unless explicitly marked open.
1open class Vehicle(val brand: String)
2
3class Bike(brand: String, val gears: Int) : Vehicle(brand)
4
5fun main() {
6 val bike = Bike("Giant", 21)
7 // ...
8}Keep sensitive state private and expose only a masked version through a method.
1class Person(val name: String, private val ssn: String) {
2 fun maskedSSN() = "XXX-XX-${ssn.takeLast(4)}"
3}
4
5fun main() {
6 val p = Person("Bob", "123-45-6789")
7 // ...
8}Implement an interface by delegation, or forward its methods manually. Delegation forwards the interface implementation for you.
1interface Greeter {
2 fun greet(name: String): String
3}
4
5class FriendlyGreeter : Greeter {
6 override fun greet(name: String) = "Hello, $name!"
7}
8
9class DelegatingGreeter : Greeter by FriendlyGreeter()
10
11class ForwardingGreeter(private val greeter: Greeter) : Greeter {
12 override fun greet(name: String) = greeter.greet(name)
13}Implement an interface and use its default method to calculate a discounted price.
1interface Discountable {
2 val price: Double
3 fun discountRate(): Double
4 fun discountedPrice(): Double = price * (1 - discountRate())
5}
6
7class Electronics(override val price: Double) : Discountable {
8 override fun discountRate() = 0.1
9}
10
11fun main() {
12 val laptop = Electronics(1000.0)
13 println(laptop.discountedPrice())
14}