Skip to content

Beginner: Kotlin · Classes, objects and collections · topic 9 of 50 · 30 min

Classes and objects

Explanation

A class is a blueprint that groups data (properties) and behaviour (functions) for one kind of thing, such as a Student or a CartItem. You create objects (instances) by calling the class like a function. Kotlin's primary constructor declares properties right in the class header with val or var, and init blocks run setup code.

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.

Think of it like this: A class is like the design of a Maruti car model: it says every car has a colour, a fuel level and can start and stop. Each car on the road is an object built from that design, with its own colour and its own fuel level.

Declaring a class with a primary constructor

kotlin
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
}
The parentheses after the class name are the primary constructor. val/var there create properties.

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

kotlin
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
    }
}
init runs when an object is created. require throws an exception with your message if the condition is false.

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

ModifierVisible to
public (default)Everyone
privateOnly inside this class (or file, for top-level items)
protectedThis class and its subclasses
internalEverything in the same module (for example, the same app module)

Custom getters

kotlin
class Rectangle(val width: Int, val height: Int) {
    val area: Int
        get() = width * height       // computed every time it is read
}
A property with a custom getter stores nothing; it is calculated.

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

Class = blueprint Object = one instance

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.

kotlin
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
}
Rules live in the class, not scattered across screens.

Practice (0/3 done)

Task 1 · Question

What does this print? class Box(val w: Int, val h: Int) { val area get() = w * h } fun main() { println(Box(3, 4).area) }

Task 2 · Question

In class User(name: String), why does user.name fail?

Task 3 · Practice

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

Question 1

1.How do you create an object of class Order in Kotlin?

Question 2

2.When does an init block run?

Question 3

3.What does private set on a property do?

Question 4

4.What is the default visibility in Kotlin?

Read more (free)

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.

From Classes, objects and constructors

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.

From Classes and constructors

What makes a class field private?Related

Answer: A leading #

#name fields are truly private; _name is only a naming convention.

From Classes

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

  1. 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.
  2. Module 3 exam: Classes, objects and collections · 14 questions · 25 min, without help. 5 topics of this module still to finish first.
  3. Then the next module, Coroutines and Flow. 50 topics left in the course before the final exam.

← Previous: Extension functions and scope functions