w3resource

Kotlin Class: Create and print person details


Write a Kotlin program that creates a class 'Person' with properties for name, age, and country. Include a function to print the person's details.


Pre-Knowledge (Before You Start!)

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

  • Classes in Kotlin: Kotlin allows you to define classes with properties and methods (functions). A class can have constructors that initialize properties when an object is created.
  • Properties: Properties in Kotlin are declared within the class and can be initialized via the constructor. They define the attributes of an object.
  • Functions inside a class: Functions can be defined within a class and can operate on the properties of the class. The this keyword can refer to the instance of the class.
  • Creating objects: Once a class is defined, you can create instances (objects) of that class using the new keyword (not required in Kotlin), simply by calling the class constructor.

Hints (Try Before Looking at the Solution!)

Try to solve the problem with these hints:

  • Hint 1: Define a class named Person with properties for name, age, and country.
  • Hint 2: Use a constructor to initialize these properties when creating a Person object.
  • Hint 3: Define a method inside the class, printDetails(), which prints the person's information.
  • Hint 4: Create an instance of the Person class in the main() function and call the printDetails() function to display the details.

Sample Solution:

Kotlin Code:

class Person(val name: String, val age: Int, val country: String) {
    fun printDetails() {
        println("Name: $name")
        println("Age: $age")
        println("Country: $country")
    }
}

fun main() {
    val person = Person("Dilara Cilla", 25, "Spain")
    person.printDetails()
}

Sample Output:

Name: Dilara Cilla
Age: 25
Country: Spain

Explanation:

In the above exercise -

  • First we define a class Person with three properties: name, age, and country. The class also includes a function printDetails() that prints the person's details by accessing the property values.
  • In the main() function, we create an instance of the Person class with the name "Dilara Cilla", age 25, and country "Spain". We then call the printDetails() function on the 'person' object to print the details.

Kotlin Editor:


Previous: Kotlin Class Exercises Home.
Next: Create and calculate rectangle area.

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.