Kotlin Classes

Learn about object-oriented programming in Kotlin.

The object-oriented programming (OOP) paradigm focuses on the creation of objects that encapsulate data and behavior. It involves the use of classes and objects, which create real-world entities and abstract concepts.

Classes and objects

Kotlin uses the class keyword followed by the name to declare a class. It uses curly brackets to enclose the body of the class, and uses properties to declare and access class members. A property is a value associated with an object, which we can read or write using some code. For instance, see the code widget below:

Press + to interact
class Person {
// Properties declaration
var name : String = ""
var age : Int = 0
// Method declaration
fun speak() {
println("Hello, my name is $name and I am $age years old.")
}
}
fun main(){
val person = Person()
person.name = "Adam"
person.age = 20
person.speak() // Output: "Hello, my name is Adam and I am 20 years old."
}

In the code above: ...