w3resource

Kotlin Class: Create and display Car information


Write a Kotlin program that creates a class 'Car' with properties for make, model, and year. Include a function to display car information.


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 that encapsulate data and behavior. You can define properties and methods inside a class.
  • Constructors: A constructor initializes the properties of a class when an object is created. In Kotlin, you can define a primary constructor directly in the class header.
  • Methods in classes: Methods (functions) inside a class operate on the properties of the class. In this exercise, a method will be used to display car details.
  • Printing information: The println() function is used to print output to the console.

Hints (Try Before Looking at the Solution!)

Try to solve the problem with these hints:

  • Hint 1: Create a class called Car with three properties: make, model, and year.
  • Hint 2: Define a function inside the class to display car details using println().
  • Hint 3: In the main() function, create an instance of the Car class and pass values for make, model, and year.
  • Hint 4: Call the method displayInfo() to print the car details.

Sample Solution:

Kotlin Code:

class Car(val make: String, val model: String, val year: Int) {
    fun displayInfo() {
        println("Car Information:")
        println("Make: $make")
        println("Model: $model")
        println("Year: $year")
    }
}

fun main() {
    val car = Car("Mercedes-Benz", "E 350 Sedan", 2021)
    car.displayInfo()
}

Sample Output:

Car Information:
Make: Mercedes-Benz
Model: E 350 Sedan
Year: 2021

Explanation:

In the above exercise -

  • First we define a class "Car" with three properties: make, model, and year. The class also includes a function displayInfo() that prints the car's make, model, and year using println() statements.
  • In the main() function, we create an instance of the "Car" class with a make of "Mercedes-Benz", model of "E 350 Sedan", and year of 2021. We then call the displayInfo() function on the car object to display car information.

Kotlin Editor:


Previous: Create and calculate rectangle area.
Next: Student class with promotion eligibility check.

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.