Advanced Kotlin Class Features

May 22 2024 · Kotlin 1.9, Android 14, Android Studio Hedgehog

Lesson 05: Define Abstract Classes

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

Open your internet browser and search for Kotlin Playground. You’ll see different websites. Select the one provided by the Android Developers page. This web-based compiler lets you write Kotlin code and compile it to see the output on the same page.

abstract class AbstractFruitBox<A, B, C, D>(
  val firstItem: A,
  val secondItem: B,
  val numOfItems: C,
  val totalCost: D
) {
}
abstract fun calculateTotalCost(): Double
fun printContents() {
  println("FruitBox contents: First Item = $firstItem, Second Item = $secondItem")
  println("Total Items = $numOfItems, Total Cost = $$totalCost")
}
class AppleBananaBox(firstItem: String, secondItem: String, numOfItems: Int, totalCost: Double) :
  AbstractFruitBox<String, String, Int, Double>(firstItem, secondItem, numOfItems, totalCost) {
}
  override fun calculateTotalCost(): Double {
    return numOfItems.toDouble() * totalCost
  }
val appleBananaBox = AppleBananaBox("Apple", "Banana", 5, 10.5)
appleBananaBox.printContents()
println("Total Cost: $${appleBananaBox.calculateTotalCost()}")
class DefaultFruitBox(firstItem: String, secondItem: String, numOfItems: Int, totalCost: Double) :
  AbstractFruitBox<String, String, Int, Double>(firstItem, secondItem, numOfItems, totalCost) {
  override fun calculateTotalCost(): Double {
    return totalCost
  }
}

class SaleFruitBox(firstItem: String, secondItem: String, numOfItems: Int, totalCost: Double, val discountPercent: Double) :
  AbstractFruitBox<String, String, Int, Double>(firstItem, secondItem, numOfItems, totalCost) {
  override fun calculateTotalCost(): Double {
    val discountedCost = totalCost * (1 - discountPercent / 100)
    return discountedCost
  }
}
val defaultFruitBox = DefaultFruitBox("Orange", "Grapes", 10, 15.0)
val saleFruitBox = SaleFruitBox("Watermelon", "Pineapple", 3, 20.0, 10.0)

appleBananaBox.printContents()
println("Total Cost (AppleBananaBox): $${appleBananaBox.calculateTotalCost()}")

defaultFruitBox.printContents()
println("Total Cost (DefaultFruitBox): $${defaultFruitBox.calculateTotalCost()}")

saleFruitBox.printContents()
println("Total Cost (SaleFruitBox): $${saleFruitBox.calculateTotalCost()}"
See forum comments
Cinema mode Download course materials from Github
Previous: Instruction Next: Conclusion