Search⌘ K
AI Features

Kotlin Classes

Explore Kotlin classes and object-oriented programming concepts crucial for Android development. Understand how to define classes, manage properties with access modifiers, and customize behavior using getters and setters. This lesson equips you to create and manipulate Kotlin objects efficiently for your apps.

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:

Kotlin
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: ...