Classes & Objects
Define classes with properties and methods, use constructors, understand inheritance and interfaces, and write Kotlin-idiomatic object-oriented code.
What Is a Class?
A class is a blueprint for creating objects. It bundles related data (properties) and behavior (functions) together.
class Dog— defines the blueprintval myDog = Dog()— creates an instance (object)
Example: a User class that holds name, age, and email.
Defining a Class
Kotlin classes have a concise primary constructor syntax:
class User(val name: String, var age: Int) {
fun greet(): String {
return "Hi, I'm $name and I'm $age years old."
}
}
fun main() {
val user = User("Alice", 28)
println(user.name) // Alice
println(user.age) // 28
user.age = 29 // var can be changed
println(user.greet())
}