Practice Time: Inheritance

 

Practice Time

Let's talk about books for a moment, those heavy tomes of paper with printed letters.

  1. Create a class, Book, with a title and an author.
  2. Add a method, readPage(), that increases the value of a private variable, currentPage, by 1.
  3. Create a subclass of Book; name it eBook.
  4. eBook also takes in a format, which defaults to "text".
  5. In eBooks, counting words makes more sense than pages. Override the readPage() method to increase the word count by 250, the average number of words per page from typewriter days.


// File:            Main.kt
// Programmer: Engineer Nolverto Urias Obeso
// Creation Date: 06/18/2023
// Email: nolvertou@gmail.com
// Description: Practicing the inheritance reading an ebook

fun main() {
val eBook = eBook("text1", "KotlinBook", "JetBrains")
eBook.readPage()
eBook.readPage()
}

Parent Class:

// TODO 1: Create a class, Book, with a title and an author.
open class Book(title: String, author: String) {
private var currentPage: Int = 0

init {
println("You started reading the book: $title written by: $author")
}

// TODO 2: Add a method, readPage(), that increases the value of a private variable, currentPage, by 1.
open fun readPage(){
currentPage++
}
}


Child Class:

// TODO 3: Create a subclass of Book; name it eBook.
// TODO 4: eBook also takes in a format, which defaults to "text".
class eBook(format: String = "text", title: String, author: String): Book(title, author) {
private var wordCount: Int = 0

// TODO 5: In eBooks, counting words makes more sense than pages. Override the readPage() method to increase the
// word count by 250, the average number of words per page from typewriter days.
override fun readPage(){
wordCount += 250
println("You have read $wordCount words")
}

}





Comments

Popular posts from this blog