w3resource

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.


Pre-Knowledge (Before You Start!)

Before attempting this exercise, you should be familiar with the following concepts:

  • Classes in Kotlin: A class is a blueprint for creating objects. It can contain properties (variables) and functions (methods) that operate on those properties.
  • Constructors: In Kotlin, a primary constructor is defined in the class header and is used to initialize the properties of an object.
  • String Interpolation: The $variable syntax allows you to insert variable values directly into a string.
  • Functions in a Class: Functions inside a class allow objects to perform specific actions. These functions can be used to display or process the class properties.
  • Creating and Using Objects: In the main() function, you can create instances of a class and call its methods.

Hints (Try Before Looking at the Solution!)

Try to solve the problem with these hints:

  • Hint 1: Create a class called Book with properties for title, author, and publicationYear.
  • Hint 2: Inside the class, define a function that prints the book details.
  • Hint 3: Use println() to display the title, author, and publication year of the book.
  • Hint 4: In the main() function, create instances of the Book class with different values.
  • Hint 5: Call the function on each book object to display its 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.



Follow us on Facebook and Twitter for latest update.