Use Kotlin Classes

May 22 2024 · Kotlin 1.9.24, Android 14, Kotlin Playground

Lesson 04: Leverage Inheritance

Demo

Episode complete

Play next episode

Next

Heads up... You’re accessing parts of this content for free, with some sections shown as obfuscated text.

Heads up... You’re accessing parts of this content for free, with some sections shown as obfuscated text.

Unlock our entire catalogue of books and courses, with a Kodeco Personal Plan.

Unlock now

In the lesson, you learned how to define subclass, which extends the behavior of the base class. Now, it’s time to see how this works in reality.


open class Food(
  val name: String,
  var price: String,
  var origin: String) {

  fun label(): String {
    return "$name of $origin. Price: $price"
  }
}

class Fruit(
  name: String,
  price: String,
  origin: String,
  val stone: Boolean = false
): Food(name, price, origin) {
  fun hasStone(): Boolean {
    return stone
  }
}

fun main() {
  val otherTomato: Food =  Fruit("Tomato", "3.0", "UK")
}
  println("otherTomato is Fruit: " + (otherTomato is Fruit)) //otherTomato is Fruit: true
  println("otherTomato is Food: " + (otherTomato is Food)) //otherTomato is Food: true

  println("otherTomato as Fruit has stone: " + (otherTomato as Fruit).hasStone()) //otherTomato as Fruit has stone: false
  println("otherTomato as maybe Fruit maybe has stone: " + (otherTomato as? Fruit)?.hasStone()) //otherTomato as maybe Fruit maybe has stone: false
See forum comments
Cinema mode Download course materials from Github
Previous: Instruction Next: Conclusion