← Back to Kotlin Course | Chapter 6: Classes & Objects | Lesson 1 of 7

Class Basics

A class is a blueprint that describes what kind of information and abilities an object should have, like a cookie cutter for making cookies.

Declaring a Simple Class

A class groups related data and behavior under one name, defined with the class keyword. Even a class with no properties or methods can be declared and instantiated.

Example: Declaring a Simple Class

markup
class Greeter {
    fun greet() {
        println("Hello from Greeter!")
    }
}

fun main() {
    val greeter = Greeter()
    greeter.greet()
}

Properties in the Primary Constructor

Declaring parameters with val or var directly in the class's parentheses creates properties automatically, avoiding the need to write separate field declarations and assignments.

Example: Properties in the Primary Constructor

markup
class Dog(val name: String, val breed: String)

fun main() {
    val dog = Dog("Rex", "Labrador")
    println("${dog.name} is a ${dog.breed}")
}

Creating Instances

An instance of a class is created by calling its name like a function, passing arguments that match its primary constructor's parameters.

Note: No new keyword is needed in Kotlin, unlike Java.

Example: Creating Instances

markup
class Point(val x: Int, val y: Int)

fun main() {
    val p1 = Point(1, 2)
    val p2 = Point(3, 4)
    println("p1=(${p1.x}, ${p1.y}), p2=(${p2.x}, ${p2.y})")
}

Member Functions

Functions declared inside a class body are member functions (methods) that operate on that instance's own properties, accessible via this implicitly.

Example: Member Functions

markup
class Circle(val radius: Double) {
    fun area(): Double = Math.PI * radius * radius
}

fun main() {
    val circle = Circle(3.0)
    println("Area: ${circle.area()}")
}
Common Mistakes
  1. Forgetting the class keyword needs a following pair of parentheses () for a primary constructor even when it has parameters, or omitting them entirely if there are none.
  2. Not realizing that properties declared in the primary constructor with val/var automatically become accessible class members.
  3. Creating an object but forgetting the () when calling the constructor, e.g. writing Dog instead of Dog().
Chapter Summary
  • A class is declared with the class keyword followed by a name and, optionally, a primary constructor.
  • Properties declared with val/var inside the constructor parentheses become class members automatically.
  • An object of a class is created by calling its constructor like a function: ClassName(...).
  • Kotlin classes are final (cannot be subclassed) by default unless marked open.
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.