Kotlin Class: Book class with display function
Write a Kotlin program that creates a class 'Book' with properties for title, author, and publication year. Include a function to display book details.
Sample Solution:
Kotlin Code:
class Book(val title: String, val author: String, val publicationYear: Int) {
fun displayBookDetails() {
println("Title: $title")
println("Author: $author")
println("Publication Year: $publicationYear")
}
}
fun main() {
val book1 = Book("Anne of Green Gables", "Lucy Maud Montgomery", 1908)
val book2 = Book("The Call of the Wild", "Jack London", 1903)
book1.displayBookDetails()
println()
book2.displayBookDetails()
}
Sample Output:
Title: Anne of Green Gables Author: Lucy Maud Montgomery Publication Year: 1908 Title: The Call of the Wild Author: Jack London Publication Year: 1903
Explanation:
In the above exercise -
- We define a class "Book" with three properties: title, author, and publicationYear. The class also includes a function displayBookDetails() that prints the book's title, author, and publication year.
- In the main() function, we create two instances of the "Book" class, book1 and book2, with different titles, authors, and publication years. We then call the displayBookDetails() function on each book object to display their details.
Kotlin Editor:
Previous: Student class with promotion eligibility check.
Next: BankAccount class with deposit and withdrawal functions.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics