CodeBlanks Logo Icon CodeBlanks

Summary - Class basics

Combine class, constructor and methods to write a User class.

Summary - Class basics

In this group you learned to declare a new type with class, create properties with the primary constructor, use val/var properties, write methods inside a class and resolve parameter-property clashes with this.

Now it is time to combine them in a small task: add a property, a method and a rename method using this to a class. This is a small sample of a real class design.

Practice Add rename and greet to Person

Define class Person(var name: String); in its body add fun greet() = "Hello $name" and fun rename(name: String) { this.name = name }. In main create val p = Person("Alex"), call p.rename("Ayşe") and print p.greet().

Starter code

Main.kt
fun main() {
    // Define a Person class with a name property, greet and rename methods
    // rename must use this; create an instance, call rename and greet
}

Sample solution

Main.kt
class Person(var name: String) {
    fun greet() = "Hello $name"
    fun rename(name: String) {
        this.name = name
    }
}

fun main() {
    val p = Person("Alex")
    p.rename("Ayşe")
    println(p.greet())
}

Expected output

Merhaba Alex

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Match tool to purpose

Term Meaning
class Class
constructor Constructor
val/var Property
fun Method

2 What does this refer to?

  • this is not used for parameters
  • this gives the current object Correct answer
  • this is a property
  • this is always required

Explanation: this refers to the current instance.

3 Fill in the blank: assign with this

Question
fun rename(name: String) {
    ____.name = name
}
Answer
fun rename(name: String) {
    this.name = name
}

Explanation: this.name refers to the property.

All lessons in Beginner