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
Transcript

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.

First, define a class called AbstractFruitBox. This class has four variables with different data types:

abstract class AbstractFruitBox<A, B, C, D>(
  val firstItem: A,
  val secondItem: B,
  val numOfItems: C,
  val totalCost: D
) {
}

Inside this class, you need to declare an abstract function called calculateTotalCost() that returns a Double value:

abstract fun calculateTotalCost(): Double

Inside this class, you must also declare a function called printContents(). You’ll use it to print some data into the console:

fun printContents() {
  println("FruitBox contents: First Item = $firstItem, Second Item = $secondItem")
  println("Total Items = $numOfItems, Total Cost = $$totalCost")
}

Now outside of the abstract class AbstractFruitBox, you’ll need to declare a new class called AppleBananaBox. This new class extends the abstract class AbstractFruitBox.

class AppleBananaBox(firstItem: String, secondItem: String, numOfItems: Int, totalCost: Double) :
  AbstractFruitBox<String, String, Int, Double>(firstItem, secondItem, numOfItems, totalCost) {
}

Here’s a code breakdown:

  • AppleBananaBox extends the AbstractFruitBox class.
  • The AbstractFruitBox class is a generic abstract class that expects four data types.
  • The values passed to the AbstractFruitBox constructor are the parameters of the AppleBananaBox primary constructor.

Next, you must override the abstract function calculateTotalCost() inside AppleBananaBox. This function performs a math operation to get the total cost of the fruits:

  override fun calculateTotalCost(): Double {
    return numOfItems.toDouble() * totalCost
  }

Now, you need to update the main() with the following code:

val appleBananaBox = AppleBananaBox("Apple", "Banana", 5, 10.5)
appleBananaBox.printContents()
println("Total Cost: $${appleBananaBox.calculateTotalCost()}")

Here’s a code breakdown:

  1. val appleBananaBox = AppleBananaBox("Apple", "Banana", 5, 10.5): Here, you create an instance of the AppleBananaBox class named appleBananaBox initialized with four values.
  2. appleBananaBox.printContents(): Here, you call the printContents() method on the appleBananaBox object. This method prints information about the contents of the appleBananaBox, including the types of fruits, the total number of items, and the total cost.
  3. println("Total Cost: $${appleBananaBox.calculateTotalCost()}"): This line prints the total cost of the items in the appleBananaBox.

Finally, run the code to see the output to the console.

Now that you understand how abstract class works, it’s time to update the example above with multiple classes to further expand your knowledge on this topic. Here’s the updated code:

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
  }
}

Here’s a code breakdown:

  1. You create a new class called DefaultFruitBox. This class overrides the calculateTotalCost() method to return the total cost of the fruits.
  2. You create another class called SaleFruitBox. This class also overrides the calculateTotalCost() method but performs a different calculation to return the total discount of the fruits.

Now, you need to update the main() function with the following code:

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()}"

Here, you create instances of DefaultFruitBox and SaleFruitBox. Then, you call printContents() to display some output in the console.

Now, run the code to see the output to the console.

See forum comments
Cinema mode Download course materials from Github
Previous: Instruction Next: Conclusion