Beginner: Kotlin · Classes, objects and collections · topic 9 of 50 · 30 min
Classes and objects
Explanation
Why classes?
Real apps deal with things: users, products, orders, bus tickets. Each thing has data (a name, a price) and actions (add to cart, cancel). A class keeps the data and the actions together in one named type. An object (or instance) is one actual thing made from the class, like one particular student.
Declaring a class with a primary constructor
class Student(val name: String, var marks: Int) {
fun result(): String = if (marks >= 33) "Pass" else "Fail"
}
fun main() {
val s = Student("Kavya", 72) // create an object: no "new" keyword
println(s.name) // Kavya
s.marks = 28 // var property can change
println(s.result()) // Fail
}A property is a value that belongs to an object. val properties are read-only after creation; var properties can change. A function inside a class is often called a method; it can use the object's properties directly.
Each object has its own copy of the properties. Changing s.marks for Kavya does not change the marks of any other Student object, just as filling one admission form does not change anyone else's form.
init blocks and validation
class BankAccount(val holder: String, initialBalance: Long) {
var balance: Long = initialBalance
private set // outside code can read but not change it
init {
require(initialBalance >= 0) { "Balance cannot be negative" }
}
fun deposit(amount: Long) {
require(amount > 0) { "Deposit must be positive" }
balance += amount
}
}Note that initialBalance has no val or var, so it is just a constructor parameter, not a property. private set lets everyone read balance but only the class itself change it, so nobody can set balance = 1_000_000 from outside.
Visibility
| Modifier | Visible to |
|---|---|
| public (default) | Everyone |
| private | Only inside this class (or file, for top-level items) |
| protected | This class and its subclasses |
| internal | Everything in the same module (for example, the same app module) |
Custom getters
class Rectangle(val width: Int, val height: Int) {
val area: Int
get() = width * height // computed every time it is read
}Secondary constructors and lateinit
Most Kotlin classes need only the primary constructor; default values usually replace extra constructors. You may meet secondary constructors (constructor(...) : this(...)) in code that talks to Java. You will also see lateinit var in Android code for properties set up a little after creation; reading one before it is set throws an exception, so use it carefully.
Common mistakes
- Writing new Student(...). Kotlin has no new keyword.
- Forgetting val or var in the constructor, then wondering why s.name does not exist.
- Making every property var and public. Start with val; expose changes through methods that check the rules.
- Putting too much in one class. A class should represent one idea.
Need help?
Stuck on a word or an idea? Search this course, or every course, and jump straight to the explanation or a worked question.
Try:
Watch the lesson
Classes and objects · 1/6
A class groups data and actions for one kind of thing. An object is one actual thing made from it.
Prefer a video by a teacher? Find free videos on “kotlin classes objects constructors properties tutorial” on YouTube ↗
In real life: A shopping cart item
In a grocery app, each line in the cart is a CartItem object with a name, a price in paise and a quantity. The class has a total property and a method to change the quantity that refuses values below 1. Every screen that shows the cart uses the same rules, so a bug cannot sneak in a quantity of zero or minus one.
class CartItem(val name: String, val pricePaise: Long, quantity: Int) {
var quantity = quantity
private set
val totalPaise: Long get() = pricePaise * quantity
fun changeQuantity(newQty: Int) {
require(newQty >= 1) { "Quantity must be at least 1" }
quantity = newQty
}
}
fun main() {
val item = CartItem("Basmati rice 5 kg", 54900, 1)
item.changeQuantity(2)
println("${item.name}: ${item.totalPaise / 100}") // Basmati rice 5 kg: 1098
}Practice (0/3 done)
What does this print? class Box(val w: Int, val h: Int) { val area get() = w * h } fun main() { println(Box(3, 4).area) }
In class User(name: String), why does user.name fail?
Write a class MetroCard(val cardId: String, initialBalance: Int) with a balance that can only be changed inside the class, methods recharge(amount) and tap(fare): Boolean (false if not enough balance), and an init block that rejects negative balances. Use it in main.
Quick quiz
Read more (free)
Related help
Before this, learn
This topic builds on these. If something here feels new, open them first.
Related topics
- Data, enum and sealed classes, and objectsClasses, objects and collections · same module
- Inheritance and interfacesClasses, objects and collections · same module
- Collections: List, Set and MapClasses, objects and collections · same module
- Classes, objects and constructorsC# and .NET · Classes and objects
- Classes and objectsPython Programming · Object-oriented programming
- Classes and constructorsFlutter and Dart · Null safety and object-oriented Dart
Questions people ask about this
Open a question to see the answer and why. The first ones are this topic's own quiz, so try the quiz above before you peek.
How do you create an object of class Order in Kotlin?
Answer: Order()
Kotlin has no new keyword.
When does an init block run?
Answer: When an object is created
init runs as part of construction.
What does private set on a property do?
Answer: Allows reading from outside but changing only inside the class
The getter stays public; the setter is private.
What is the default visibility in Kotlin?
Answer: public
Declarations are public unless you say otherwise.
What does : this(name, 0m) after a constructor header do?Related
Answer: Calls another constructor of the same class first
It chains to another constructor to reuse its setup code.
What happens if marks = [] is written in the class body and each student appends to self.marks?Related
Answer: All students share one list
A class attribute is shared. Mutable per-object data must be created in __init__.
From Classes and objects
Why do Flutter widgets often use const constructors?Related
Answer: Constant widgets are created once and can be skipped during rebuilds
const saves work at run time.
What makes a class field private?Related
Pass the quiz (60% or more) or mark this topic as done when you are ready.
Your progress is saved on this device only.
Next steps
- 4 more topics in “Classes, objects and collections” before its exam: Data, enum and sealed classes, and objects, Inheritance and interfaces, Collections: List, Set and Map, Collection operations.
- Module 3 exam: Classes, objects and collections · 14 questions · 25 min, without help. 5 topics of this module still to finish first.
- Then the next module, Coroutines and Flow. 50 topics left in the course before the final exam.