Course map
Stage 1: Foundation
Stage 2: Intermediate
Stage 3: Advanced
Stage 4: DSA in Kotlin
Stage 5: Specialization

Part 07 / Stage 1

Classes and objects

Goal: Write a plain class by hand -- a primary constructor, properties, init blocks for validation, a second way to build the same object with a secondary constructor, this for the current instance, custom getters/setters, and the three visibility modifiers that actually matter without inheritance yet. Time: ~6 hours · Level: comfortable with functions (Part 5) and collections (Part 6)

🔍 Going deeper: this part deliberately stops at a plain class. No data class, no interface, no object/companion object, no subclassing -- those all show up together in Stage 2, Part 9, once you've felt what writing a class by hand costs and have something real to compare them against.

What you will learn

  • Declaring a class with a primary constructor, and how val/var constructor parameters become properties automatically
  • init blocks: code that runs once, right when an object is built, usually to validate it -- and that a class can have more than one, running in the order they're written
  • Secondary constructors: a second (or third) way to build the same class, always delegating to the primary constructor with : this(...)
  • this: referring to the current instance, telling a property apart from a same-named parameter, and returning it from a method to chain calls
  • Custom getters and setters, the field keyword for the real backing storage, and private set for a property anyone can read but only the class itself can change
  • The three visibility modifiers that make sense before inheritance exists: public (the default), private, and internal
  • Building a single-class bank account: constructors, validation, a private transaction log, and deposit/withdraw/mini-statement methods

Topics in this part

Practice

Try each one yourself first. Then check the solution.

Every exercise is one file with a top-level fun main(), using what Parts 1-7 have covered so far: val/var, basic types, null safety, control flow, functions, collections, and this part's classes, constructors, init blocks, custom getters/setters and visibility modifiers. No inheritance, no data class, no object/companion object -- those start in Stage 2, Part 9.


Exercise 1: Student record

Scenario: a school keeps one record per student: name, roll number, and marks that get updated after each exam. What to do: write class Student(val name: String, val rollNumber: Int) with a var marks: Int = 0 property and a printDetails() method. Create a student, print their details, update marks, and print again.

Sample output:

Kabir Singh (roll no. 21) -- marks: 0
Kabir Singh (roll no. 21) -- marks: 87

💡 Hint: rollNumber and name can be val constructor parameters; marks is a separate var property declared in the class body, not in the constructor.


Exercise 2: Movie ticket

Scenario: a cinema's booking system prints a ticket, and sometimes adjusts the price (a weekend surcharge) after it's booked. What to do: write class MovieTicket(val movieName: String, val seatNumber: String, var price: Double) with a printBooking() method. Book a ticket, print it, change price, print again.

Sample output:

Pathaan -- seat G12 -- ₹250.0
Pathaan -- seat G12 -- ₹300.0

💡 Hint: since price is a primary-constructor var, ticket.price = 300.0 is all it takes to change it -- no setter method needed yet.


Exercise 3: Hiring age check

Scenario: an HR system must never create an Employee record for someone under 18. What to do: write class Employee(val name: String, val age: Int) with an init block that requires age >= 18, printing a hire confirmation when it passes. Hire one valid employee, then try to construct one aged 16 and catch the IllegalArgumentException.

Sample output:

Hired Rohan Verma, age 24
Rejected: age must be 18 or above, was 16

💡 Hint: require(age >= 18) { "age must be 18 or above, was $age" } throws with that exact message when the condition is false.


Exercise 4: Address with a short form

Scenario: a delivery form usually has a full address, but sometimes only a city and pincode are known at first, with the rest filled in later. What to do: write class Address(val houseNo: String, val street: String, val city: String, val pincode: String) with a printAddress() method, plus a secondary constructor Address(city: String, pincode: String) that delegates to the primary one with "Not specified" for the house number and street.

Sample output:

12B, MG Road, Pune - 411001
Not specified, Not specified, Nagpur - 440001

💡 Hint: constructor(city: String, pincode: String) : this("Not specified", "Not specified", city, pincode).


Exercise 5: Product with a guarded price

Scenario: a store's product catalog must never let a price go negative, and always needs a computed discounted price alongside it. What to do: write class Product(val name: String, price: Double) with a var price: Double property whose setter rejects a negative value via require, plus a val discountedPrice: Double computed getter returning 10% off the current price. Print both, change price, print again, then try setting a negative price and catch the exception.

Sample output:

Mixer Grinder: ₹2000.0, discounted: ₹1800.0
Mixer Grinder: ₹1800.0, discounted: ₹1620.0
Rejected: price cannot be negative, got -100.0

💡 Hint: the setter needs field = value as its last line once validation passes, or the new price never actually sticks; the constructor's own price parameter needs the same require check in an init block, since the setter alone doesn't run for the very first value.


Exercise 6: Wallet with a private balance

Scenario: a digital wallet must let any code read the balance, but only the wallet's own deposit/withdraw methods may ever change it. What to do: write class Wallet(val owner: String) with var balance: Double = 0.0 using private set, a deposit(amount: Double) that validates and adds to it, and a withdraw(amount: Double): Boolean that returns false instead of throwing when the amount is invalid or exceeds the balance. Deposit, make one successful and one failed withdrawal, printing the balance after each.

Sample output:

Nisha Patil's balance: ₹1000.0
Withdrawal of ₹400 succeeded: true, balance now ₹600.0
Withdrawal of ₹5000 succeeded: false, balance now ₹600.0

💡 Hint: wallet.balance = 999999.0 written anywhere outside the class should not compile -- that's the point of private set, not something to work around.


Exercise 7: Playlist with chained adds

Scenario: building up a playlist one song at a time reads better as one chained expression than three separate statements. What to do: write class Playlist(val name: String) with a private val songs = mutableListOf<String>(), a secondary constructor Playlist(name: String, firstSong: String) that seeds the first song, an addSong(song: String): Playlist that adds the song and returns this, and a printSongs() method. Build a playlist by chaining addSong calls off the secondary constructor's result, then print it.

Sample output:

Road Trip: [Kesariya, Tum Hi Ho, Jai Ho]

💡 Hint: inside the secondary constructor's body, this.songs.add(firstSong) reaches the private list that already exists because the primary constructor ran first; addSong must return this, not Unit, for the chain to work.


Exercise 8: Library membership

Scenario: a library caps how many books a member can borrow at once, tracks what they currently have out, and refuses a borrow past the limit. What to do: write class LibraryMembership(val memberName: String, maxBooks: Int) with an init block requiring maxBooks > 0, a private val borrowedBooks = mutableListOf<String>(), a secondary constructor LibraryMembership(memberName: String) defaulting maxBooks to 3, a val booksBorrowed: Int computed getter, and borrowBook(title: String): Boolean / returnBook(title: String): Boolean methods that print what happened and return whether it succeeded. Borrow four books on a standard (3-book) membership, check the count, return one, borrow again, and try returning a book that was never borrowed.

Sample output:

Dev Ahuja borrowed "The Alchemist".
Dev Ahuja borrowed "Wings of Fire".
Dev Ahuja borrowed "Sapiens".
Dev Ahuja has reached the limit of 3 books.
Books currently borrowed: 3
Dev Ahuja returned "Wings of Fire".
Dev Ahuja borrowed "Think and Grow Rich".
Dev Ahuja never borrowed "Atomic Habits".

💡 Hint: borrowedBooks.remove(title) already returns true/false for "was it there to remove" -- that's exactly what returnBook needs to report, no separate contains check required.

Show the solutions for Part 7 (8 files)

solutions/ex01.kt

class Student(val name: String, val rollNumber: Int) {
    var marks: Int = 0

    fun printDetails() {
        println("$name (roll no. $rollNumber) -- marks: $marks")
    }
}

fun main() {
    val student = Student("Kabir Singh", 21)
    student.printDetails()

    student.marks = 87
    student.printDetails()
}

solutions/ex02.kt

class MovieTicket(val movieName: String, val seatNumber: String, var price: Double) {
    fun printBooking() {
        println("$movieName -- seat $seatNumber -- ₹$price")
    }
}

fun main() {
    val ticket = MovieTicket("Pathaan", "G12", 250.0)
    ticket.printBooking()

    ticket.price = 300.0   // weekend surcharge
    ticket.printBooking()
}

solutions/ex03.kt

class Employee(val name: String, val age: Int) {
    init {
        require(age >= 18) { "age must be 18 or above, was $age" }
        println("Hired $name, age $age")
    }
}

fun main() {
    val employee = Employee("Rohan Verma", 24)

    try {
        Employee("Tanvi", 16)
    } catch (e: IllegalArgumentException) {
        println("Rejected: ${e.message}")
    }
}

solutions/ex04.kt

class Address(val houseNo: String, val street: String, val city: String, val pincode: String) {
    constructor(city: String, pincode: String) : this("Not specified", "Not specified", city, pincode)

    fun printAddress() {
        println("$houseNo, $street, $city - $pincode")
    }
}

fun main() {
    val full = Address("12B", "MG Road", "Pune", "411001")
    full.printAddress()

    val partial = Address("Nagpur", "440001")
    partial.printAddress()
}

solutions/ex05.kt

class Product(val name: String, price: Double) {
    var price: Double = price
        set(value) {
            require(value >= 0.0) { "price cannot be negative, got $value" }
            field = value
        }

    val discountedPrice: Double
        get() = price * 0.9

    init {
        require(price >= 0.0) { "price cannot be negative, got $price" }
    }
}

fun main() {
    val product = Product("Mixer Grinder", 2000.0)
    println("${product.name}: ₹${product.price}, discounted: ₹${product.discountedPrice}")

    product.price = 1800.0
    println("${product.name}: ₹${product.price}, discounted: ₹${product.discountedPrice}")

    try {
        product.price = -100.0
    } catch (e: IllegalArgumentException) {
        println("Rejected: ${e.message}")
    }
}

solutions/ex06.kt

class Wallet(val owner: String) {
    var balance: Double = 0.0
        private set

    fun deposit(amount: Double) {
        require(amount > 0.0) { "deposit amount must be positive" }
        balance += amount
    }

    fun withdraw(amount: Double): Boolean {
        if (amount <= 0.0 || amount > balance) return false
        balance -= amount
        return true
    }
}

fun main() {
    val wallet = Wallet("Nisha Patil")
    wallet.deposit(1000.0)
    println("${wallet.owner}'s balance: ₹${wallet.balance}")

    val ok = wallet.withdraw(400.0)
    println("Withdrawal of ₹400 succeeded: $ok, balance now ₹${wallet.balance}")

    val failed = wallet.withdraw(5000.0)
    println("Withdrawal of ₹5000 succeeded: $failed, balance now ₹${wallet.balance}")

    // wallet.balance = 999999.0   // would not compile: the setter is private outside the class
}

solutions/ex07.kt

class Playlist(val name: String) {
    private val songs = mutableListOf<String>()

    constructor(name: String, firstSong: String) : this(name) {
        this.songs.add(firstSong)
    }

    fun addSong(song: String): Playlist {
        songs.add(song)
        return this
    }

    fun printSongs() {
        println("$name: $songs")
    }
}

fun main() {
    val playlist = Playlist("Road Trip", "Kesariya")
        .addSong("Tum Hi Ho")
        .addSong("Jai Ho")

    playlist.printSongs()
}

solutions/ex08.kt

class LibraryMembership(val memberName: String, maxBooks: Int) {
    var maxBooks: Int = maxBooks
        private set

    private val borrowedBooks = mutableListOf<String>()

    init {
        require(maxBooks > 0) { "maxBooks must be positive, was $maxBooks" }
    }

    // secondary constructor: a standard membership caps out at 3 books
    constructor(memberName: String) : this(memberName, 3)

    val booksBorrowed: Int
        get() = borrowedBooks.size

    fun borrowBook(title: String): Boolean {
        if (borrowedBooks.size >= maxBooks) {
            println("$memberName has reached the limit of $maxBooks books.")
            return false
        }
        borrowedBooks.add(title)
        println("$memberName borrowed \"$title\".")
        return true
    }

    fun returnBook(title: String): Boolean {
        val removed = borrowedBooks.remove(title)
        if (removed) {
            println("$memberName returned \"$title\".")
        } else {
            println("$memberName never borrowed \"$title\".")
        }
        return removed
    }
}

fun main() {
    val member = LibraryMembership("Dev Ahuja")
    member.borrowBook("The Alchemist")
    member.borrowBook("Wings of Fire")
    member.borrowBook("Sapiens")
    member.borrowBook("Think and Grow Rich")   // over the limit of 3

    println("Books currently borrowed: ${member.booksBorrowed}")

    member.returnBook("Wings of Fire")
    member.borrowBook("Think and Grow Rich")   // now there's room again
    member.returnBook("Atomic Habits")          // was never borrowed
}

Common mistakes

Mistake Why it is wrong Fix
Writing class Account(name: String) and expecting account.name to work Without val/var, a primary constructor parameter is just a parameter -- it isn't a property at all Write val name: String (or var) in the constructor if you want it to be a readable property
A secondary constructor that sets fields directly instead of delegating Kotlin requires every secondary constructor to call this(...) -- it won't compile otherwise Always start it with : this(...), delegating to the primary constructor (maybe through another secondary one)
Writing a custom setter and forgetting field = value The new value is validated but never actually stored -- the property silently keeps its old value End the setter body with field = value once validation passes
Making every property var with a public setter "to be safe" Anyone can then put the object into an invalid state from outside, bypassing your validation Use private set (or a val) and expose a method (deposit, withdraw) that validates before changing it
Expecting internal to behave like private internal is visible everywhere in the current module -- in Stage 1, with no Gradle/multi-module project, that's your whole program Use private when the real intent is "only this class", internal only once you have a real module boundary (Stage 2's Gradle projects)
Confusing this.balance = balance disambiguation with primary-constructor val/var parameters val/var constructor parameters never need this. -- they already become the property automatically Reach for this.propertyName = parameterName only when a secondary constructor or method has a same-named parameter and a non-constructor property
Validating in a method instead of init A caller can build an already-invalid object by skipping straight to field access before calling anything Put constructor-time checks (require) in init, so an invalid object can never exist in the first place

Quick recap

  • val/var primary-constructor parameters become real properties automatically; plain parameters (no val/var) only live through construction.
  • init blocks run at construction time, in the order written, and are the right place for require-style validation.
  • A secondary constructor always delegates to the primary constructor via : this(...), directly or through another secondary constructor.
  • this disambiguates a property from a same-named parameter, and lets a method return the current object for chaining.
  • A custom getter runs fresh on every read; a custom setter must assign field = value itself, or the new value never sticks; private set makes a property externally read-only.
  • public (default), internal (whole module), and private (this class only) cover everything Stage 1 needs; protected waits for Stage 2's inheritance.
  • A require(condition) { "message" } failing throws IllegalArgumentException with that message -- the standard way to reject bad constructor input.

Checklist

  • I declared a class with a primary constructor using val/var parameters, and created more than one instance to confirm each has its own property values.
  • I wrote an init block that rejects bad input with require, and caught the resulting IllegalArgumentException.
  • I wrote a secondary constructor that delegates to the primary one with : this(...).
  • I used this to disambiguate a property from a same-named parameter, and to return the current object from a method for chaining.
  • I wrote a custom setter that validates and assigns field = value, and a private set property that I could read but not assign from outside the class.
  • I tried accessing a private member from outside its class myself and watched the compiler reject it.
  • I built and ran the bank account myself, including an insufficient-balance withdrawal and an invalid PIN change.

Search the guide