๐ŸŽ“ A1Learner
๐Ÿ”

Kotlin Classes

A class is a plan for making objects that hold values and can do actions. Each object made from the plan holds its own copy of those values.

Making an object from a class

The list after the class name is its primary constructor. It names the properties each new Dog starts with.

class Dog(val name: String, var age: Int)

fun main() {
    val dog = Dog("Rex", 3)
    println(dog.name)
    println(dog.age)
}

A method inside the class

bark is a method because its fun sits inside the class braces. A dot joins the object to the method call.

class Dog(val name: String, var age: Int) {
    fun bark() {
        println("$name says woof")
    }
}

fun main() {
    val dog = Dog("Rex", 3)
    dog.bark()
}

Changing a var property

age is a var property, so a new value can replace the old one. Both prints show the age of the same dog.

class Dog(val name: String, var age: Int)

fun main() {
    val dog = Dog("Rex", 3)
    println(dog.age)
    dog.age = 4
    println(dog.age)
}

Two objects live separate lives

Each object keeps its own age value. Changing the first dog leaves the second dog at its starting age.

class Dog(val name: String, var age: Int)

fun main() {
    val first = Dog("Rex", 3)
    val second = Dog("Pip", 1)
    first.age = 5
    println(first.age)
    println(second.age)
}

Example

class Dog(val name: String, var age: Int) {
    fun haveBirthday() {
        age++
        println("$name is now $age")
    }
}

fun main() {
    val rex = Dog("Rex", 3)
    val pip = Dog("Pip", 1)
    rex.haveBirthday()
    println(pip.age)
}

Key points

  • Use the class name with starting values to make an object.
  • A property is a value stored inside an object.
  • A primary constructor is the list of properties written after the class name.
  • A var property can change after the object is made.
  • A val property stays fixed after the object is made.
  • A method is a function written inside a class.

In this example, rex and pip are two objects made from the Dog plan. The birthday call adds 1 to the age of rex and prints Rex is now 4. Pip never gets that call, so the last print shows the age of pip as 1.

Note

Kotlin needs no new keyword to make an object, unlike Java.

Try it Yourself

Edit the code, then press Run.

Running is simulated ยท Kotlin Playground

Exercise

What is an object made from a class?