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

Part 07 / Topic 1 of 7

Declaring a class with a primary constructor

A class is a blueprint for objects that bundle data and behaviour together. The primary constructor sits right in the class header, and every parameter written with val or var becomes a real property on the object -- no separate assignment needed.

class Student(val name: String, val rollNumber: Int) {
    // a property that is NOT in the primary constructor -- it gets a default,
    // and can be changed later because it's a var
    var attendancePercent: Double = 100.0

    fun printDetails() {
        println("$name (roll no. $rollNumber) -- attendance: $attendancePercent%")
    }
}
val asha = Student("Asha Kulkarni", 7)
val ravi = Student("Ravi Shah", 12)

asha.printDetails()
ravi.printDetails()

ravi.attendancePercent = 92.5
ravi.printDetails()

println("asha.attendancePercent is still ${asha.attendancePercent}")
Asha Kulkarni (roll no. 7) -- attendance: 100.0%
Ravi Shah (roll no. 12) -- attendance: 100.0%
Ravi Shah (roll no. 12) -- attendance: 92.5%
asha.attendancePercent is still 100.0

Each call to Student(...) creates a fresh object with its own copy of the properties -- changing ravi.attendancePercent never touches asha. val name/val rollNumber are read-only once the object exists: asha.rollNumber = 9 simply does not compile.

Real-world example: a Student, a Product, a MovieTicket -- anything your program needs to track as "one thing with several fields that belong together" is a candidate for a class, the same way Part 6 reached for a Map when the shape was "values under keys".

Full program: examples/01_declaring_classes.kt.

Done here? The practice set for Part 7 — including the solutions — is on the part page.

Search the guide