Kotlin Classes and Objects
Classes are the blueprints of Kotlin OOP, and objects are the actual instances built from those blueprints.
Declaring a Class
A class is declared with the class keyword followed by a name. By convention, class names start with an uppercase letter. The simplest class can be completely empty, but most classes declare properties and functions inside curly braces.
A Minimal Class
class Person
fun main() {
val person = Person()
println(person)
}Properties
Properties are variables that belong to a class. They can be declared with val (read-only, like a final field) or var (mutable). Kotlin automatically generates getters for val properties and getters plus setters for var properties, so you rarely write boilerplate accessor methods yourself.
Class With Properties
class Person {
var name: String = ""
var age: Int = 0
}
fun main() {
val p = Person()
p.name = "Maya"
p.age = 29
println("${p.name} is ${p.age} years old")
}Creating Objects
An object is created by calling the class name as if it were a function - notice there is no 'new' keyword in Kotlin, unlike Java or C#. Each call to the class constructor produces a distinct object with its own copy of the properties.
- A class is a template; it exists once in your code
- An object is an instance of that template; you can create many
- Each object has independent state unless properties are shared via companion objects
- Objects are created without the 'new' keyword in Kotlin
Multiple Independent Objects
class Counter {
var count: Int = 0
fun increment() { count++ }
}
fun main() {
val a = Counter()
val b = Counter()
a.increment()
a.increment()
b.increment()
println("a=${a.count}, b=${b.count}")
}Member Access
You access an object's properties and functions using dot notation: object.property or object.function(). This is the same syntax used across most OOP languages, which makes Kotlin approachable if you've used Java, C#, or Swift before.
Next, you'll learn how constructors let you set property values right when an object is created, instead of assigning them one by one afterward.
Exercise: Kotlin Classes and Objects
How do you create a new instance of a class in Kotlin?