100% Free Forever
AI-Powered Learning
Industry Expert Content
Certificates & Badges
Learn At Your Own Pace
Kotlin

Classes in Kotlin

Learn how Kotlin classes bundle state and behavior with concise constructor syntax and final-by-default semantics.

Classes & ObjectsBeginner8 min readJul 8, 2026
Analogies

Introduction

A class in Kotlin is a blueprint for creating objects that combine properties (state) and functions (behavior). Kotlin classes are more concise than Java classes because the primary constructor and property declarations can be merged directly into the class header, eliminating a lot of boilerplate getter, setter, and field code.

🏏

Cricket analogy: A Kotlin class is like a player's scouting profile: batting average and bowling style (properties) plus training routine (functions) are bundled into one concise dossier instead of scattered team-manager notes.

Syntax

kotlin
class Person(val name: String, var age: Int) {
    fun greet() {
        println("Hi, I'm $name and I'm $age years old.")
    }
}

Explanation

Here, name and age are declared directly inside the parentheses of the class header, which is the primary constructor. Prefixing a parameter with val or var automatically creates a property on the class with a generated getter (and setter for var). The class body, enclosed in curly braces, can hold additional functions and properties. Unlike Java, a class in Kotlin is final by default, meaning it cannot be subclassed unless explicitly marked open.

🏏

Cricket analogy: Declaring name and age in the constructor is like the IPL auction listing a player's role and base price directly on the auction card, auto-generating the scoreboard entry without a separate registration form; and just as a player is 'final' unless a franchise explicitly retains rights to develop them further, a Kotlin class can't be subclassed unless marked open.

Example

kotlin
class Person(val name: String, var age: Int) {
    fun greet() {
        println("Hi, I'm $name and I'm $age years old.")
    }
}

fun main() {
    val alice = Person("Alice", 30)
    alice.greet()
    alice.age = 31
    println("New age: ${alice.age}")
}

Output

text
Hi, I'm Alice and I'm 30 years old.
New age: 31

Key Takeaways

  • A class bundles properties and functions into a single reusable blueprint.
  • Properties declared with val/var in the primary constructor get automatic getters/setters.
  • Kotlin classes are final by default, unlike Java classes which are open by default.
  • The class body can add extra functions, properties, and initializer logic.
  • Instantiation requires no new keyword, e.g. Person("Alice", 30).

Practice what you learned

Was this page helpful?

Topics covered

#Kotlin#KotlinProgrammingStudyNotes#Programming#ClassesInKotlin#Classes#Syntax#Explanation#Example#OOP#StudyNotes#SkillVeris