Introduction to Kotlin Object-Oriented Programming

May 22 2024 · Kotlin 1.9.21, Android 14, Kotlin Playground & Android Studio Hedgehog | 2023.1.1

Lesson 04: Abstract Classes & Interfaces

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 this demo, you’ll make MuseumObject conform to the Comparable interface from the Kotlin standard library. Then, you’ll create an interface and a subclass of MuseumObject that adopts it.

open class MuseumObject(
  //...
): Comparable<MuseumObject> {
  //...
}
// return when {
//   objectID > other.objectID -> 1
//   objectID == other.objectID -> 0
//   else -> -1
// }
return objectID.compareTo(other.objectID)
val obj =
  MuseumObject(
    objectID = 436535,
    title = "Wheat Field with Cypresses",
    objectURL = "https://www.metmuseum.org/art/collection/search/436535",
//    primaryImageSmall = "https://images.metmuseum.org/CRDImages/ep/original/DT1567.jpg",
    creditLine = "Purchase, The Annenberg Foundation Gift, 1993",
    isPublicDomain = true
  )

val obj_pd =
  PublicDomainObject(
    objectID = 436535,
    title = "Wheat Field with Cypresses",
    objectURL = "https://www.metmuseum.org/art/collection/search/436535",
    primaryImageSmall = "https://images.metmuseum.org/CRDImages/ep/original/DT1567.jpg",
    creditLine = "Purchase, The Annenberg Foundation Gift, 1993",
  )
println("COMPARE ${obj > obj_pd}")
val obj2 =
  MuseumObject(
    objectID = 11521,
    title = "Afternoon among the Cypress",
    objectURL = "https://www.metmuseum.org/art/collection/search/11521",
    creditLine = "Gift of Mrs. Henrietta Zeile, 1909",
    isPublicDomain = false
  )
println("COMPARE 2 ${obj > obj2}")
obj2.showImage()
interface OnDisplay {
  val galleryNumber: String
  fun showMap(from: String, to: String)
}
class OnDisplayObject(
  objectID: Int,
  title: String,
  objectURL: String,
  creditLine: String,
  isPublicDomain: Boolean = true,
  override val galleryNumber: String, // Overriden property
) : MuseumObject(objectID, title, objectURL, creditLine, isPublicDomain), OnDisplay {

}
override fun showMap(from: String, to: String) {
  galleryNumber.takeIf { it.isNotEmpty() } ?: return
  // implementation here
}
val obj_od =
  OnDisplayObject(
    objectID = 436535,
    title = "Wheat Field with Cypresses",
    objectURL = "https://www.metmuseum.org/art/collection/search/436535",
    creditLine = "Purchase, The Annenberg Foundation Gift, 1993",
    galleryNumber = "822"
  )
obj_od.showImage()
See forum comments
Cinema mode Download course materials from Github
Previous: Instruction Next: Conclusion