w3resource

Kotlin Class: Create and display Car information

Kotlin Class: Exercise-3 with Solution

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

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.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://w3resource.com/kotlin-exercises/class/kotlin-class-exercise-3.php